Ruby  2.5.0dev(2017-10-22revision60238)
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  */
36 static void
37 ossl_hmac_free(void *ctx)
38 {
39  HMAC_CTX_free(ctx);
40 }
41 
42 static const rb_data_type_t ossl_hmac_type = {
43  "OpenSSL/HMAC",
44  {
45  0, ossl_hmac_free,
46  },
48 };
49 
50 static VALUE
51 ossl_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  */
101 static VALUE
102 ossl_hmac_initialize(VALUE self, VALUE key, VALUE digest)
103 {
104  HMAC_CTX *ctx;
105 
106  StringValue(key);
107  GetHMAC(self, ctx);
108  HMAC_Init_ex(ctx, RSTRING_PTR(key), RSTRING_LENINT(key),
110 
111  return self;
112 }
113 
114 static VALUE
115 ossl_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  */
148 static VALUE
149 ossl_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 
160 static void
161 hmac_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  */
190 static VALUE
191 ossl_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  */
213 static VALUE
214 ossl_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  */
248 static VALUE
249 ossl_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  */
276 static VALUE
277 ossl_hmac_s_digest(VALUE klass, VALUE digest, VALUE key, VALUE data)
278 {
279  unsigned char *buf;
280  unsigned int buf_len;
281 
282  StringValue(key);
283  StringValue(data);
284  buf = HMAC(ossl_evp_get_digestbyname(digest), RSTRING_PTR(key),
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  */
308 static VALUE
309 ossl_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 
315  StringValue(key);
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  */
332 void
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 <<<
390 void
391 Init_ossl_hmac(void)
392 {
393  rb_warning("HMAC is not available: OpenSSL is compiled without HMAC.");
394 }
395 #endif /* NO_HMAC */
#define GetHMAC(obj, ctx)
Definition: ossl_hmac.c:16
VALUE mOSSL
Definition: ossl.c:231
#define RUBY_TYPED_FREE_IMMEDIATELY
Definition: ruby.h:1138
VALUE cHMAC
Definition: ossl_hmac.c:26
void rb_define_singleton_method(VALUE obj, const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a singleton method for obj.
Definition: class.c:1716
#define HMAC_CTX_new
void rb_str_set_len(VALUE, long)
Definition: string.c:2627
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition: class.c:693
void rb_define_alloc_func(VALUE, rb_alloc_func_t)
VALUE eHMACError
Definition: ossl_hmac.c:27
#define NewHMAC(klass)
Definition: ossl_hmac.c:14
RUBY_EXTERN VALUE rb_cObject
Definition: ruby.h:1893
VALUE eOSSLError
Definition: ossl.c:236
void Init_ossl_hmac(void)
Definition: ossl_hmac.c:333
#define HMAC_CTX_free
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition: class.c:1758
#define RSTRING_LEN(str)
Definition: ruby.h:971
const EVP_MD * ossl_evp_get_digestbyname(VALUE obj)
Definition: ossl_digest.c:45
unsigned char buf[MIME_BUF_SIZE]
Definition: nkf.c:4309
VALUE rb_eStandardError
Definition: error.c:799
unsigned long VALUE
Definition: ruby.h:85
void ossl_bin2hex(unsigned char *in, char *out, size_t inlen)
Definition: ossl.c:133
#define RSTRING_PTR(str)
Definition: ruby.h:975
void rb_warning(const char *fmt,...)
Definition: error.c:267
void ossl_raise(VALUE exc, const char *fmt,...)
Definition: ossl.c:293
#define assert
Definition: ruby_assert.h:37
#define RTYPEDDATA_DATA(v)
Definition: ruby.h:1110
#define RSTRING_LENINT(str)
Definition: ruby.h:983
#define rb_check_frozen(obj)
Definition: intern.h:271
VALUE rb_define_module(const char *name)
Definition: class.c:768
#define NULL
Definition: _sdbm.c:102
void rb_define_method(VALUE klass, const char *name, VALUE(*func)(ANYARGS), int argc)
Definition: class.c:1515
#define StringValue(v)
Definition: ruby.h:569
VALUE rb_str_new(const char *, long)
Definition: string.c:737