Ruby 2.7.7p221 (2022-11-24 revision 168ec2b1e5ad0e4688e963d9de019557c78feed9)
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 */
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 },
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)
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 won't be equal when they're compared, even if they have the
88 * same value. Use #to_s or #hexdigest to return the authentication code that
89 * the instance represents. For example:
90 *
91 * other_instance = OpenSSL::HMAC.new('key', OpenSSL::Digest.new('sha1'))
92 * #=> f42bb0eeb018ebbd4597ae7213711ec60760843f
93 * instance
94 * #=> f42bb0eeb018ebbd4597ae7213711ec60760843f
95 * instance == other_instance
96 * #=> false
97 * instance.to_s == other_instance.to_s
98 * #=> true
99 *
100 */
101static VALUE
102ossl_hmac_initialize(VALUE self, VALUE key, VALUE digest)
103{
104 HMAC_CTX *ctx;
105
107 GetHMAC(self, ctx);
108 HMAC_Init_ex(ctx, RSTRING_PTR(key), RSTRING_LENINT(key),
110
111 return self;
112}
113
114static VALUE
115ossl_hmac_copy(VALUE self, VALUE other)
116{
117 HMAC_CTX *ctx1, *ctx2;
118
119 rb_check_frozen(self);
120 if (self == other) return self;
121
122 GetHMAC(self, ctx1);
123 GetHMAC(other, ctx2);
124
125 if (!HMAC_CTX_copy(ctx1, ctx2))
126 ossl_raise(eHMACError, "HMAC_CTX_copy");
127 return self;
128}
129
130/*
131 * call-seq:
132 * hmac.update(string) -> self
133 *
134 * Returns _hmac_ updated with the message to be authenticated.
135 * Can be called repeatedly with chunks of the message.
136 *
137 * === Example
138 *
139 * first_chunk = 'The quick brown fox jumps '
140 * second_chunk = 'over the lazy dog'
141 *
142 * instance.update(first_chunk)
143 * #=> 5b9a8038a65d571076d97fe783989e52278a492a
144 * instance.update(second_chunk)
145 * #=> de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9
146 *
147 */
148static VALUE
149ossl_hmac_update(VALUE self, VALUE data)
150{
151 HMAC_CTX *ctx;
152
153 StringValue(data);
154 GetHMAC(self, ctx);
155 HMAC_Update(ctx, (unsigned char *)RSTRING_PTR(data), RSTRING_LEN(data));
156
157 return self;
158}
159
160static void
161hmac_final(HMAC_CTX *ctx, unsigned char *buf, unsigned int *buf_len)
162{
163 HMAC_CTX *final;
164
165 final = HMAC_CTX_new();
166 if (!final)
167 ossl_raise(eHMACError, "HMAC_CTX_new");
168
169 if (!HMAC_CTX_copy(final, ctx)) {
170 HMAC_CTX_free(final);
171 ossl_raise(eHMACError, "HMAC_CTX_copy");
172 }
173
174 HMAC_Final(final, buf, buf_len);
175 HMAC_CTX_free(final);
176}
177
178/*
179 * call-seq:
180 * hmac.digest -> string
181 *
182 * Returns the authentication code an instance represents as a binary string.
183 *
184 * === Example
185 * instance = OpenSSL::HMAC.new('key', OpenSSL::Digest.new('sha1'))
186 * #=> f42bb0eeb018ebbd4597ae7213711ec60760843f
187 * instance.digest
188 * #=> "\xF4+\xB0\xEE\xB0\x18\xEB\xBDE\x97\xAEr\x13q\x1E\xC6\a`\x84?"
189 */
190static VALUE
191ossl_hmac_digest(VALUE self)
192{
193 HMAC_CTX *ctx;
194 unsigned int buf_len;
195 VALUE ret;
196
197 GetHMAC(self, ctx);
198 ret = rb_str_new(NULL, EVP_MAX_MD_SIZE);
199 hmac_final(ctx, (unsigned char *)RSTRING_PTR(ret), &buf_len);
200 assert(buf_len <= EVP_MAX_MD_SIZE);
201 rb_str_set_len(ret, buf_len);
202
203 return ret;
204}
205
206/*
207 * call-seq:
208 * hmac.hexdigest -> string
209 *
210 * Returns the authentication code an instance represents as a hex-encoded
211 * string.
212 */
213static VALUE
214ossl_hmac_hexdigest(VALUE self)
215{
216 HMAC_CTX *ctx;
217 unsigned char buf[EVP_MAX_MD_SIZE];
218 unsigned int buf_len;
219 VALUE ret;
220
221 GetHMAC(self, ctx);
222 hmac_final(ctx, buf, &buf_len);
223 ret = rb_str_new(NULL, buf_len * 2);
224 ossl_bin2hex(buf, RSTRING_PTR(ret), buf_len);
225
226 return ret;
227}
228
229/*
230 * call-seq:
231 * hmac.reset -> self
232 *
233 * Returns _hmac_ as it was when it was first initialized, with all processed
234 * data cleared from it.
235 *
236 * === Example
237 *
238 * data = "The quick brown fox jumps over the lazy dog"
239 * instance = OpenSSL::HMAC.new('key', OpenSSL::Digest.new('sha1'))
240 * #=> f42bb0eeb018ebbd4597ae7213711ec60760843f
241 *
242 * instance.update(data)
243 * #=> de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9
244 * instance.reset
245 * #=> f42bb0eeb018ebbd4597ae7213711ec60760843f
246 *
247 */
248static VALUE
249ossl_hmac_reset(VALUE self)
250{
251 HMAC_CTX *ctx;
252
253 GetHMAC(self, ctx);
254 HMAC_Init_ex(ctx, NULL, 0, NULL, NULL);
255
256 return self;
257}
258
259/*
260 * call-seq:
261 * HMAC.digest(digest, key, data) -> aString
262 *
263 * Returns the authentication code as a binary string. The _digest_ parameter
264 * specifies the digest algorithm to use. This may be a String representing
265 * the algorithm name or an instance of OpenSSL::Digest.
266 *
267 * === Example
268 *
269 * key = 'key'
270 * data = 'The quick brown fox jumps over the lazy dog'
271 *
272 * hmac = OpenSSL::HMAC.digest('sha1', key, data)
273 * #=> "\xDE|\x9B\x85\xB8\xB7\x8A\xA6\xBC\x8Az6\xF7\n\x90p\x1C\x9D\xB4\xD9"
274 *
275 */
276static VALUE
277ossl_hmac_s_digest(VALUE klass, VALUE digest, VALUE key, VALUE data)
278{
279 unsigned char *buf;
280 unsigned int buf_len;
281
283 StringValue(data);
285 RSTRING_LENINT(key), (unsigned char *)RSTRING_PTR(data),
286 RSTRING_LEN(data), NULL, &buf_len);
287
288 return rb_str_new((const char *)buf, buf_len);
289}
290
291/*
292 * call-seq:
293 * HMAC.hexdigest(digest, key, data) -> aString
294 *
295 * Returns the authentication code as a hex-encoded string. The _digest_
296 * parameter specifies the digest algorithm to use. This may be a String
297 * representing the algorithm name or an instance of OpenSSL::Digest.
298 *
299 * === Example
300 *
301 * key = 'key'
302 * data = 'The quick brown fox jumps over the lazy dog'
303 *
304 * hmac = OpenSSL::HMAC.hexdigest('sha1', key, data)
305 * #=> "de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9"
306 *
307 */
308static VALUE
309ossl_hmac_s_hexdigest(VALUE klass, VALUE digest, VALUE key, VALUE data)
310{
311 unsigned char buf[EVP_MAX_MD_SIZE];
312 unsigned int buf_len;
313 VALUE ret;
314
316 StringValue(data);
317
318 if (!HMAC(ossl_evp_get_digestbyname(digest), RSTRING_PTR(key),
319 RSTRING_LENINT(key), (unsigned char *)RSTRING_PTR(data),
320 RSTRING_LEN(data), buf, &buf_len))
321 ossl_raise(eHMACError, "HMAC");
322
323 ret = rb_str_new(NULL, buf_len * 2);
324 ossl_bin2hex(buf, RSTRING_PTR(ret), buf_len);
325
326 return ret;
327}
328
329/*
330 * INIT
331 */
332void
334{
335#if 0
336 mOSSL = rb_define_module("OpenSSL");
338#endif
339
340 /*
341 * Document-class: OpenSSL::HMAC
342 *
343 * OpenSSL::HMAC allows computing Hash-based Message Authentication Code
344 * (HMAC). It is a type of message authentication code (MAC) involving a
345 * hash function in combination with a key. HMAC can be used to verify the
346 * integrity of a message as well as the authenticity.
347 *
348 * OpenSSL::HMAC has a similar interface to OpenSSL::Digest.
349 *
350 * === HMAC-SHA256 using one-shot interface
351 *
352 * key = "key"
353 * data = "message-to-be-authenticated"
354 * mac = OpenSSL::HMAC.hexdigest("SHA256", key, data)
355 * #=> "cddb0db23f469c8bf072b21fd837149bd6ace9ab771cceef14c9e517cc93282e"
356 *
357 * === HMAC-SHA256 using incremental interface
358 *
359 * data1 = File.read("file1")
360 * data2 = File.read("file2")
361 * key = "key"
362 * digest = OpenSSL::Digest::SHA256.new
363 * hmac = OpenSSL::HMAC.new(key, digest)
364 * hmac << data1
365 * hmac << data2
366 * mac = hmac.digest
367 */
369
371
372 rb_define_alloc_func(cHMAC, ossl_hmac_alloc);
373 rb_define_singleton_method(cHMAC, "digest", ossl_hmac_s_digest, 3);
374 rb_define_singleton_method(cHMAC, "hexdigest", ossl_hmac_s_hexdigest, 3);
375
376 rb_define_method(cHMAC, "initialize", ossl_hmac_initialize, 2);
377 rb_define_method(cHMAC, "initialize_copy", ossl_hmac_copy, 1);
378
379 rb_define_method(cHMAC, "reset", ossl_hmac_reset, 0);
380 rb_define_method(cHMAC, "update", ossl_hmac_update, 1);
381 rb_define_alias(cHMAC, "<<", "update");
382 rb_define_method(cHMAC, "digest", ossl_hmac_digest, 0);
383 rb_define_method(cHMAC, "hexdigest", ossl_hmac_hexdigest, 0);
384 rb_define_alias(cHMAC, "inspect", "hexdigest");
385 rb_define_alias(cHMAC, "to_s", "hexdigest");
386}
387
388#else /* NO_HMAC */
389# warning >>> OpenSSL is compiled without HMAC support <<<
390void
391Init_ossl_hmac(void)
392{
393 rb_warning("HMAC is not available: OpenSSL is compiled without HMAC.");
394}
395#endif /* NO_HMAC */
VALUE rb_define_class_under(VALUE, const char *, VALUE)
Defines a class under the namespace of outer.
Definition: class.c:711
VALUE rb_define_module(const char *)
Definition: class.c:785
void rb_define_alias(VALUE, const char *, const char *)
Defines an alias of a method.
Definition: class.c:1818
VALUE rb_cObject
Object class.
Definition: ruby.h:2012
VALUE rb_eStandardError
Definition: error.c:921
#define HMAC_CTX_new
#define HMAC_CTX_free
void ossl_bin2hex(unsigned char *in, char *out, size_t inlen)
Definition: ossl.c:133
VALUE mOSSL
Definition: ossl.c:231
void ossl_raise(VALUE exc, const char *fmt,...)
Definition: ossl.c:293
VALUE eOSSLError
Definition: ossl.c:236
const EVP_MD * ossl_evp_get_digestbyname(VALUE obj)
Definition: ossl_digest.c:45
#define NewHMAC(klass)
Definition: ossl_hmac.c:14
void Init_ossl_hmac(void)
Definition: ossl_hmac.c:333
VALUE eHMACError
Definition: ossl_hmac.c:27
VALUE cHMAC
Definition: ossl_hmac.c:26
#define GetHMAC(obj, ctx)
Definition: ossl_hmac.c:16
#define NULL
use StringValue() instead")))
#define RSTRING_LEN(str)
const VALUE VALUE obj
#define rb_check_frozen(obj)
#define RSTRING_PTR(str)
#define RTYPEDDATA_DATA(v)
#define rb_str_new(str, len)
#define RSTRING_LENINT(str)
void rb_str_set_len(VALUE, long)
Definition: string.c:2692
unsigned long VALUE
void rb_define_alloc_func(VALUE, rb_alloc_func_t)
void rb_define_singleton_method(VALUE, const char *, VALUE(*)(), int)
#define RUBY_TYPED_FREE_IMMEDIATELY
struct rb_call_cache buf
#define assert
const char *void rb_warning(const char *,...) __attribute__((format(printf
void rb_define_method(VALUE, const char *, VALUE(*)(), int)