Ruby: ext/openssl/ossl_hmac.c Source File

Ruby 3.0.5p211 (2022-11-24 revision ba5cf0f7c52d4d35cc6a173c89eda98ceffa2dcf)

ossl_hmac.c
Go to the documentation of this file.
1/*
2 * 'OpenSSL for Ruby' project
3 * Copyright (C) 2001-2002 Michal Rokos <m.rokos@sh.cvut.cz>
4 * All rights reserved.
5 */
6/*
7 * This program is licensed under the same licence as Ruby.
8 * (See the file 'LICENCE'.)
9 */
10#if !defined(OPENSSL_NO_HMAC)
11
12#include "ossl.h"
13
14#define NewHMAC(klass) \
15 TypedData_Wrap_Struct((klass), &ossl_hmac_type, 0)
16#define GetHMAC(obj, ctx) do { \
17 TypedData_Get_Struct((obj), HMAC_CTX, &ossl_hmac_type, (ctx)); \
18 if (!(ctx)) { \
19 ossl_raise(rb_eRuntimeError, "HMAC wasn't initialized"); \
20 } \
21} while (0)
22
23/*
24 * Classes
25 */
26 VALUE cHMAC;
27 VALUE eHMACError;
28
29/*
30 * Public
31 */
32
33/*
34 * Private
35 */
36static void
37ossl_hmac_free(void *ctx)
38{
39 HMAC_CTX_free(ctx);
40}
41
42static const rb_data_type_t ossl_hmac_type = {
43 "OpenSSL/HMAC",
44 {
45 0, ossl_hmac_free,
46 },
47 0, 0, RUBY_TYPED_FREE_IMMEDIATELY,
48};
49
50static VALUE
51ossl_hmac_alloc(VALUE klass)
52{
53 VALUE obj;
54 HMAC_CTX *ctx;
55
56 obj = NewHMAC(klass);
57 ctx = HMAC_CTX_new();
58 if (!ctx)
59 ossl_raise(eHMACError, NULL);
60 RTYPEDDATA_DATA(obj) = ctx;
61
62 return obj;
63}
64
65
66/*
67 * call-seq:
68 * HMAC.new(key, digest) -> hmac
69 *
70 * Returns an instance of OpenSSL::HMAC set with the key and digest
71 * algorithm to be used. The instance represents the initial state of
72 * the message authentication code before any data has been processed.
73 * To process data with it, use the instance method #update with your
74 * data as an argument.
75 *
76 * === Example
77 *
78 * key = 'key'
79 * digest = OpenSSL::Digest.new('sha1')
80 * instance = OpenSSL::HMAC.new(key, digest)
81 * #=> f42bb0eeb018ebbd4597ae7213711ec60760843f
82 * instance.class
83 * #=> OpenSSL::HMAC
84 *
85 * === A note about comparisons
86 *
87 * Two instances can be securely compared with #== in constant time:
88 *
89 * other_instance = OpenSSL::HMAC.new('key', OpenSSL::Digest.new('sha1'))
90 * #=> f42bb0eeb018ebbd4597ae7213711ec60760843f
91 * instance == other_instance
92 * #=> true
93 *
94 */
95static VALUE
96ossl_hmac_initialize(VALUE self, VALUE key, VALUE digest)
97{
98 HMAC_CTX *ctx;
99
100 StringValue(key);
101 GetHMAC(self, ctx);
102 HMAC_Init_ex(ctx, RSTRING_PTR(key), RSTRING_LENINT(key),
103 ossl_evp_get_digestbyname(digest), NULL);
104
105 return self;
106}
107
108static VALUE
109ossl_hmac_copy(VALUE self, VALUE other)
110{
111 HMAC_CTX *ctx1, *ctx2;
112
113 rb_check_frozen(self);
114 if (self == other) return self;
115
116 GetHMAC(self, ctx1);
117 GetHMAC(other, ctx2);
118
119 if (!HMAC_CTX_copy(ctx1, ctx2))
120 ossl_raise(eHMACError, "HMAC_CTX_copy");
121 return self;
122}
123
124/*
125 * call-seq:
126 * hmac.update(string) -> self
127 *
128 * Returns _hmac_ updated with the message to be authenticated.
129 * Can be called repeatedly with chunks of the message.
130 *
131 * === Example
132 *
133 * first_chunk = 'The quick brown fox jumps '
134 * second_chunk = 'over the lazy dog'
135 *
136 * instance.update(first_chunk)
137 * #=> 5b9a8038a65d571076d97fe783989e52278a492a
138 * instance.update(second_chunk)
139 * #=> de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9
140 *
141 */
142static VALUE
143ossl_hmac_update(VALUE self, VALUE data)
144{
145 HMAC_CTX *ctx;
146
147 StringValue(data);
148 GetHMAC(self, ctx);
149 HMAC_Update(ctx, (unsigned char *)RSTRING_PTR(data), RSTRING_LEN(data));
150
151 return self;
152}
153
154static void
155hmac_final(HMAC_CTX *ctx, unsigned char *buf, unsigned int *buf_len)
156{
157 HMAC_CTX *final;
158
159 final = HMAC_CTX_new();
160 if (!final)
161 ossl_raise(eHMACError, "HMAC_CTX_new");
162
163 if (!HMAC_CTX_copy(final, ctx)) {
164 HMAC_CTX_free(final);
165 ossl_raise(eHMACError, "HMAC_CTX_copy");
166 }
167
168 HMAC_Final(final, buf, buf_len);
169 HMAC_CTX_free(final);
170}
171
172/*
173 * call-seq:
174 * hmac.digest -> string
175 *
176 * Returns the authentication code an instance represents as a binary string.
177 *
178 * === Example
179 * instance = OpenSSL::HMAC.new('key', OpenSSL::Digest.new('sha1'))
180 * #=> f42bb0eeb018ebbd4597ae7213711ec60760843f
181 * instance.digest
182 * #=> "\xF4+\xB0\xEE\xB0\x18\xEB\xBDE\x97\xAEr\x13q\x1E\xC6\a`\x84?"
183 */
184static VALUE
185ossl_hmac_digest(VALUE self)
186{
187 HMAC_CTX *ctx;
188 unsigned int buf_len;
189 VALUE ret;
190
191 GetHMAC(self, ctx);
192 ret = rb_str_new(NULL, EVP_MAX_MD_SIZE);
193 hmac_final(ctx, (unsigned char *)RSTRING_PTR(ret), &buf_len);
194 assert(buf_len <= EVP_MAX_MD_SIZE);
195 rb_str_set_len(ret, buf_len);
196
197 return ret;
198}
199
200/*
201 * call-seq:
202 * hmac.hexdigest -> string
203 *
204 * Returns the authentication code an instance represents as a hex-encoded
205 * string.
206 */
207static VALUE
208ossl_hmac_hexdigest(VALUE self)
209{
210 HMAC_CTX *ctx;
211 unsigned char buf[EVP_MAX_MD_SIZE];
212 unsigned int buf_len;
213 VALUE ret;
214
215 GetHMAC(self, ctx);
216 hmac_final(ctx, buf, &buf_len);
217 ret = rb_str_new(NULL, buf_len * 2);
218 ossl_bin2hex(buf, RSTRING_PTR(ret), buf_len);
219
220 return ret;
221}
222
223/*
224 * call-seq:
225 * hmac.reset -> self
226 *
227 * Returns _hmac_ as it was when it was first initialized, with all processed
228 * data cleared from it.
229 *
230 * === Example
231 *
232 * data = "The quick brown fox jumps over the lazy dog"
233 * instance = OpenSSL::HMAC.new('key', OpenSSL::Digest.new('sha1'))
234 * #=> f42bb0eeb018ebbd4597ae7213711ec60760843f
235 *
236 * instance.update(data)
237 * #=> de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9
238 * instance.reset
239 * #=> f42bb0eeb018ebbd4597ae7213711ec60760843f
240 *
241 */
242static VALUE
243ossl_hmac_reset(VALUE self)
244{
245 HMAC_CTX *ctx;
246
247 GetHMAC(self, ctx);
248 HMAC_Init_ex(ctx, NULL, 0, NULL, NULL);
249
250 return self;
251}
252
253/*
254 * call-seq:
255 * HMAC.digest(digest, key, data) -> aString
256 *
257 * Returns the authentication code as a binary string. The _digest_ parameter
258 * specifies the digest algorithm to use. This may be a String representing
259 * the algorithm name or an instance of OpenSSL::Digest.
260 *
261 * === Example
262 *
263 * key = 'key'
264 * data = 'The quick brown fox jumps over the lazy dog'
265 *
266 * hmac = OpenSSL::HMAC.digest('sha1', key, data)
267 * #=> "\xDE|\x9B\x85\xB8\xB7\x8A\xA6\xBC\x8Az6\xF7\n\x90p\x1C\x9D\xB4\xD9"
268 *
269 */
270static VALUE
271ossl_hmac_s_digest(VALUE klass, VALUE digest, VALUE key, VALUE data)
272{
273 unsigned char *buf;
274 unsigned int buf_len;
275
276 StringValue(key);
277 StringValue(data);
278 buf = HMAC(ossl_evp_get_digestbyname(digest), RSTRING_PTR(key),
279 RSTRING_LENINT(key), (unsigned char *)RSTRING_PTR(data),
280 RSTRING_LEN(data), NULL, &buf_len);
281
282 return rb_str_new((const char *)buf, buf_len);
283}
284
285/*
286 * call-seq:
287 * HMAC.hexdigest(digest, key, data) -> aString
288 *
289 * Returns the authentication code as a hex-encoded string. The _digest_
290 * parameter specifies the digest algorithm to use. This may be a String
291 * representing the algorithm name or an instance of OpenSSL::Digest.
292 *
293 * === Example
294 *
295 * key = 'key'
296 * data = 'The quick brown fox jumps over the lazy dog'
297 *
298 * hmac = OpenSSL::HMAC.hexdigest('sha1', key, data)
299 * #=> "de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9"
300 *
301 */
302static VALUE
303ossl_hmac_s_hexdigest(VALUE klass, VALUE digest, VALUE key, VALUE data)
304{
305 unsigned char buf[EVP_MAX_MD_SIZE];
306 unsigned int buf_len;
307 VALUE ret;
308
309 StringValue(key);
310 StringValue(data);
311
312 if (!HMAC(ossl_evp_get_digestbyname(digest), RSTRING_PTR(key),
313 RSTRING_LENINT(key), (unsigned char *)RSTRING_PTR(data),
314 RSTRING_LEN(data), buf, &buf_len))
315 ossl_raise(eHMACError, "HMAC");
316
317 ret = rb_str_new(NULL, buf_len * 2);
318 ossl_bin2hex(buf, RSTRING_PTR(ret), buf_len);
319
320 return ret;
321}
322
323/*
324 * INIT
325 */
326void
327Init_ossl_hmac(void)
328{
329#if 0
330 mOSSL = rb_define_module("OpenSSL");
331 eOSSLError = rb_define_class_under(mOSSL, "OpenSSLError", rb_eStandardError);
332#endif
333
334 /*
335 * Document-class: OpenSSL::HMAC
336 *
337 * OpenSSL::HMAC allows computing Hash-based Message Authentication Code
338 * (HMAC). It is a type of message authentication code (MAC) involving a
339 * hash function in combination with a key. HMAC can be used to verify the
340 * integrity of a message as well as the authenticity.
341 *
342 * OpenSSL::HMAC has a similar interface to OpenSSL::Digest.
343 *
344 * === HMAC-SHA256 using one-shot interface
345 *
346 * key = "key"
347 * data = "message-to-be-authenticated"
348 * mac = OpenSSL::HMAC.hexdigest("SHA256", key, data)
349 * #=> "cddb0db23f469c8bf072b21fd837149bd6ace9ab771cceef14c9e517cc93282e"
350 *
351 * === HMAC-SHA256 using incremental interface
352 *
353 * data1 = File.read("file1")
354 * data2 = File.read("file2")
355 * key = "key"
356 * digest = OpenSSL::Digest.new('SHA256')
357 * hmac = OpenSSL::HMAC.new(key, digest)
358 * hmac << data1
359 * hmac << data2
360 * mac = hmac.digest
361 */
362 eHMACError = rb_define_class_under(mOSSL, "HMACError", eOSSLError);
363
364 cHMAC = rb_define_class_under(mOSSL, "HMAC", rb_cObject);
365
366 rb_define_alloc_func(cHMAC, ossl_hmac_alloc);
367 rb_define_singleton_method(cHMAC, "digest", ossl_hmac_s_digest, 3);
368 rb_define_singleton_method(cHMAC, "hexdigest", ossl_hmac_s_hexdigest, 3);
369
370 rb_define_method(cHMAC, "initialize", ossl_hmac_initialize, 2);
371 rb_define_method(cHMAC, "initialize_copy", ossl_hmac_copy, 1);
372
373 rb_define_method(cHMAC, "reset", ossl_hmac_reset, 0);
374 rb_define_method(cHMAC, "update", ossl_hmac_update, 1);
375 rb_define_alias(cHMAC, "<<", "update");
376 rb_define_method(cHMAC, "digest", ossl_hmac_digest, 0);
377 rb_define_method(cHMAC, "hexdigest", ossl_hmac_hexdigest, 0);
378 rb_define_alias(cHMAC, "inspect", "hexdigest");
379 rb_define_alias(cHMAC, "to_s", "hexdigest");
380}
381
382#else /* NO_HMAC */
383# warning >>> OpenSSL is compiled without HMAC support <<<
384void
385 Init_ossl_hmac(void)
386{
387 rb_warning("HMAC is not available: OpenSSL is compiled without HMAC.");
388}
389#endif /* NO_HMAC */
rb_define_method
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
Definition: cxxanyargs.hpp:653
rb_define_singleton_method
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
Definition: cxxanyargs.hpp:668
assert
#define assert(x)
Definition: dlmalloc.c:1176
RSTRING_LEN
#define RSTRING_LEN(string)
Definition: fbuffer.h:22
RSTRING_PTR
#define RSTRING_PTR(string)
Definition: fbuffer.h:19
rb_define_class_under
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition: class.c:797
rb_define_module
VALUE rb_define_module(const char *name)
Definition: class.c:871
rb_define_alias
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition: class.c:1999
rb_eStandardError
VALUE rb_eStandardError
Definition: error.c:1054
rb_warning
void rb_warning(const char *fmt,...)
Definition: error.c:439
rb_cObject
VALUE rb_cObject
Object class.
Definition: object.c:49
rb_check_frozen
#define rb_check_frozen
Definition: error.h:72
rb_str_new
#define rb_str_new(str, len)
Definition: string.h:213
rb_str_set_len
void rb_str_set_len(VALUE, long)
Definition: string.c:2842
rb_define_alloc_func
void rb_define_alloc_func(VALUE, rb_alloc_func_t)
buf
voidpf void * buf
Definition: ioapi.h:138
key
key
Definition: openssl_missing.h:185
HMAC_CTX_new
#define HMAC_CTX_new
Definition: openssl_missing.h:59
HMAC_CTX_free
#define HMAC_CTX_free
Definition: openssl_missing.h:64
ossl_bin2hex
void ossl_bin2hex(unsigned char *in, char *out, size_t inlen)
Definition: ossl.c:133
mOSSL
VALUE mOSSL
Definition: ossl.c:231
ossl_raise
void ossl_raise(VALUE exc, const char *fmt,...)
Definition: ossl.c:293
eOSSLError
VALUE eOSSLError
Definition: ossl.c:236
ossl.h
ossl_evp_get_digestbyname
const EVP_MD * ossl_evp_get_digestbyname(VALUE obj)
Definition: ossl_digest.c:45
NewHMAC
#define NewHMAC(klass)
Definition: ossl_hmac.c:14
Init_ossl_hmac
void Init_ossl_hmac(void)
Definition: ossl_hmac.c:327
eHMACError
VALUE eHMACError
Definition: ossl_hmac.c:27
cHMAC
VALUE cHMAC
Definition: ossl_hmac.c:26
GetHMAC
#define GetHMAC(obj, ctx)
Definition: ossl_hmac.c:16
NULL
#define NULL
Definition: regenc.h:69
StringValue
#define StringValue(v)
Definition: rstring.h:50
RTYPEDDATA_DATA
#define RTYPEDDATA_DATA(v)
Definition: rtypeddata.h:47
RUBY_TYPED_FREE_IMMEDIATELY
@ RUBY_TYPED_FREE_IMMEDIATELY
Definition: rtypeddata.h:62
rb_data_type_struct
Definition: rtypeddata.h:70
VALUE
unsigned long VALUE
Definition: value.h:38