Ruby  2.0.0p648(2015-12-16revision53162)
ossl_cipher.c
Go to the documentation of this file.
1 /*
2  * $Id: ossl_cipher.c 49249 2015-01-14 07:25:48Z usa $
3  * 'OpenSSL for Ruby' project
4  * Copyright (C) 2001-2002 Michal Rokos <m.rokos@sh.cvut.cz>
5  * All rights reserved.
6  */
7 /*
8  * This program is licenced under the same licence as Ruby.
9  * (See the file 'LICENCE'.)
10  */
11 #include "ossl.h"
12 
13 #define WrapCipher(obj, klass, ctx) \
14  (obj) = Data_Wrap_Struct((klass), 0, ossl_cipher_free, (ctx))
15 #define MakeCipher(obj, klass, ctx) \
16  (obj) = Data_Make_Struct((klass), EVP_CIPHER_CTX, 0, ossl_cipher_free, (ctx))
17 #define AllocCipher(obj, ctx) \
18  memset(DATA_PTR(obj) = (ctx) = ALLOC(EVP_CIPHER_CTX), 0, sizeof(EVP_CIPHER_CTX))
19 #define GetCipherInit(obj, ctx) do { \
20  Data_Get_Struct((obj), EVP_CIPHER_CTX, (ctx)); \
21 } while (0)
22 #define GetCipher(obj, ctx) do { \
23  GetCipherInit((obj), (ctx)); \
24  if (!(ctx)) { \
25  ossl_raise(rb_eRuntimeError, "Cipher not inititalized!"); \
26  } \
27 } while (0)
28 #define SafeGetCipher(obj, ctx) do { \
29  OSSL_Check_Kind((obj), cCipher); \
30  GetCipher((obj), (ctx)); \
31 } while (0)
32 
33 /*
34  * Classes
35  */
38 static ID id_key_set;
39 
40 static VALUE ossl_cipher_alloc(VALUE klass);
41 
42 /*
43  * PUBLIC
44  */
45 const EVP_CIPHER *
47 {
48  EVP_CIPHER_CTX *ctx;
49 
50  SafeGetCipher(obj, ctx);
51 
52  return EVP_CIPHER_CTX_cipher(ctx);
53 }
54 
55 VALUE
56 ossl_cipher_new(const EVP_CIPHER *cipher)
57 {
58  VALUE ret;
59  EVP_CIPHER_CTX *ctx;
60 
62  AllocCipher(ret, ctx);
63  EVP_CIPHER_CTX_init(ctx);
64  if (EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, -1) != 1)
66 
67  return ret;
68 }
69 
70 /*
71  * PRIVATE
72  */
73 static void
74 ossl_cipher_free(EVP_CIPHER_CTX *ctx)
75 {
76  if (ctx) {
77  EVP_CIPHER_CTX_cleanup(ctx);
78  ruby_xfree(ctx);
79  }
80 }
81 
82 static VALUE
84 {
85  VALUE obj;
86 
87  WrapCipher(obj, klass, 0);
88 
89  return obj;
90 }
91 
92 /*
93  * call-seq:
94  * Cipher.new(string) -> cipher
95  *
96  * The string must contain a valid cipher name like "AES-128-CBC" or "3DES".
97  *
98  * A list of cipher names is available by calling OpenSSL::Cipher.ciphers.
99  */
100 static VALUE
102 {
103  EVP_CIPHER_CTX *ctx;
104  const EVP_CIPHER *cipher;
105  char *name;
106 
107  name = StringValuePtr(str);
108  GetCipherInit(self, ctx);
109  if (ctx) {
110  ossl_raise(rb_eRuntimeError, "Cipher already inititalized!");
111  }
112  AllocCipher(self, ctx);
113  EVP_CIPHER_CTX_init(ctx);
114  if (!(cipher = EVP_get_cipherbyname(name))) {
115  ossl_raise(rb_eRuntimeError, "unsupported cipher algorithm (%s)", name);
116  }
117  if (EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, -1) != 1)
119 
120  return self;
121 }
122 
123 static VALUE
125 {
126  EVP_CIPHER_CTX *ctx1, *ctx2;
127 
128  rb_check_frozen(self);
129  if (self == other) return self;
130 
131  GetCipherInit(self, ctx1);
132  if (!ctx1) {
133  AllocCipher(self, ctx1);
134  }
135  SafeGetCipher(other, ctx2);
136  if (EVP_CIPHER_CTX_copy(ctx1, ctx2) != 1)
138 
139  return self;
140 }
141 
142 #ifdef HAVE_OBJ_NAME_DO_ALL_SORTED
143 static void*
144 add_cipher_name_to_ary(const OBJ_NAME *name, VALUE ary)
145 {
146  rb_ary_push(ary, rb_str_new2(name->name));
147  return NULL;
148 }
149 #endif
150 
151 #ifdef HAVE_OBJ_NAME_DO_ALL_SORTED
152 /*
153  * call-seq:
154  * Cipher.ciphers -> array[string...]
155  *
156  * Returns the names of all available ciphers in an array.
157  */
158 static VALUE
159 ossl_s_ciphers(VALUE self)
160 {
161  VALUE ary;
162 
163  ary = rb_ary_new();
164  OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH,
165  (void(*)(const OBJ_NAME*,void*))add_cipher_name_to_ary,
166  (void*)ary);
167 
168  return ary;
169 }
170 #else
171 #define ossl_s_ciphers rb_f_notimplement
172 #endif
173 
174 /*
175  * call-seq:
176  * cipher.reset -> self
177  *
178  * Fully resets the internal state of the Cipher. By using this, the same
179  * Cipher instance may be used several times for en- or decryption tasks.
180  *
181  * Internally calls EVP_CipherInit_ex(ctx, NULL, NULL, NULL, NULL, -1).
182  */
183 static VALUE
185 {
186  EVP_CIPHER_CTX *ctx;
187 
188  GetCipher(self, ctx);
189  if (EVP_CipherInit_ex(ctx, NULL, NULL, NULL, NULL, -1) != 1)
191 
192  return self;
193 }
194 
195 static VALUE
196 ossl_cipher_init(int argc, VALUE *argv, VALUE self, int mode)
197 {
198  EVP_CIPHER_CTX *ctx;
199  unsigned char key[EVP_MAX_KEY_LENGTH], *p_key = NULL;
200  unsigned char iv[EVP_MAX_IV_LENGTH], *p_iv = NULL;
201  VALUE pass, init_v;
202 
203  if(rb_scan_args(argc, argv, "02", &pass, &init_v) > 0){
204  /*
205  * oops. this code mistakes salt for IV.
206  * We deprecated the arguments for this method, but we decided
207  * keeping this behaviour for backward compatibility.
208  */
209  VALUE cname = rb_class_path(rb_obj_class(self));
210  rb_warn("arguments for %"PRIsVALUE"#encrypt and %"PRIsVALUE"#decrypt were deprecated; "
211  "use %"PRIsVALUE"#pkcs5_keyivgen to derive key and IV",
212  cname, cname, cname);
213  StringValue(pass);
214  GetCipher(self, ctx);
215  if (NIL_P(init_v)) memcpy(iv, "OpenSSL for Ruby rulez!", sizeof(iv));
216  else{
217  StringValue(init_v);
218  if (EVP_MAX_IV_LENGTH > RSTRING_LEN(init_v)) {
219  memset(iv, 0, EVP_MAX_IV_LENGTH);
220  memcpy(iv, RSTRING_PTR(init_v), RSTRING_LEN(init_v));
221  }
222  else memcpy(iv, RSTRING_PTR(init_v), sizeof(iv));
223  }
224  EVP_BytesToKey(EVP_CIPHER_CTX_cipher(ctx), EVP_md5(), iv,
225  (unsigned char *)RSTRING_PTR(pass), RSTRING_LENINT(pass), 1, key, NULL);
226  p_key = key;
227  p_iv = iv;
228  }
229  else {
230  GetCipher(self, ctx);
231  }
232  if (EVP_CipherInit_ex(ctx, NULL, NULL, p_key, p_iv, mode) != 1) {
234  }
235  if (p_key)
236  rb_ivar_set(self, id_key_set, Qtrue);
237  return self;
238 }
239 
240 /*
241  * call-seq:
242  * cipher.encrypt -> self
243  *
244  * Initializes the Cipher for encryption.
245  *
246  * Make sure to call Cipher#encrypt or Cipher#decrypt before using any of the
247  * following methods:
248  * * [key=, iv=, random_key, random_iv, pkcs5_keyivgen]
249  *
250  * Internally calls EVP_CipherInit_ex(ctx, NULL, NULL, NULL, NULL, 1).
251  */
252 static VALUE
254 {
255  return ossl_cipher_init(argc, argv, self, 1);
256 }
257 
258 /*
259  * call-seq:
260  * cipher.decrypt -> self
261  *
262  * Initializes the Cipher for decryption.
263  *
264  * Make sure to call Cipher#encrypt or Cipher#decrypt before using any of the
265  * following methods:
266  * * [key=, iv=, random_key, random_iv, pkcs5_keyivgen]
267  *
268  * Internally calls EVP_CipherInit_ex(ctx, NULL, NULL, NULL, NULL, 0).
269  */
270 static VALUE
272 {
273  return ossl_cipher_init(argc, argv, self, 0);
274 }
275 
276 /*
277  * call-seq:
278  * cipher.pkcs5_keyivgen(pass [, salt [, iterations [, digest]]] ) -> nil
279  *
280  * Generates and sets the key/IV based on a password.
281  *
282  * WARNING: This method is only PKCS5 v1.5 compliant when using RC2, RC4-40,
283  * or DES with MD5 or SHA1. Using anything else (like AES) will generate the
284  * key/iv using an OpenSSL specific method. This method is deprecated and
285  * should no longer be used. Use a PKCS5 v2 key generation method from
286  * OpenSSL::PKCS5 instead.
287  *
288  * === Parameters
289  * +salt+ must be an 8 byte string if provided.
290  * +iterations+ is a integer with a default of 2048.
291  * +digest+ is a Digest object that defaults to 'MD5'
292  *
293  * A minimum of 1000 iterations is recommended.
294  *
295  */
296 static VALUE
298 {
299  EVP_CIPHER_CTX *ctx;
300  const EVP_MD *digest;
301  VALUE vpass, vsalt, viter, vdigest;
302  unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH], *salt = NULL;
303  int iter;
304 
305  rb_scan_args(argc, argv, "13", &vpass, &vsalt, &viter, &vdigest);
306  StringValue(vpass);
307  if(!NIL_P(vsalt)){
308  StringValue(vsalt);
309  if(RSTRING_LEN(vsalt) != PKCS5_SALT_LEN)
310  ossl_raise(eCipherError, "salt must be an 8-octet string");
311  salt = (unsigned char *)RSTRING_PTR(vsalt);
312  }
313  iter = NIL_P(viter) ? 2048 : NUM2INT(viter);
314  digest = NIL_P(vdigest) ? EVP_md5() : GetDigestPtr(vdigest);
315  GetCipher(self, ctx);
316  EVP_BytesToKey(EVP_CIPHER_CTX_cipher(ctx), digest, salt,
317  (unsigned char *)RSTRING_PTR(vpass), RSTRING_LENINT(vpass), iter, key, iv);
318  if (EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, -1) != 1)
320  OPENSSL_cleanse(key, sizeof key);
321  OPENSSL_cleanse(iv, sizeof iv);
322 
323  rb_ivar_set(self, id_key_set, Qtrue);
324  return Qnil;
325 }
326 
327 static int
328 ossl_cipher_update_long(EVP_CIPHER_CTX *ctx, unsigned char *out, long *out_len_ptr,
329  const unsigned char *in, long in_len)
330 {
331  int out_part_len;
332  long out_len = 0;
333 #define UPDATE_LENGTH_LIMIT INT_MAX
334 
335 #if SIZEOF_LONG > UPDATE_LENGTH_LIMIT
336  if (in_len > UPDATE_LENGTH_LIMIT) {
337  const int in_part_len = (UPDATE_LENGTH_LIMIT / 2 + 1) & ~1;
338  do {
339  if (!EVP_CipherUpdate(ctx, out ? (out + out_len) : 0,
340  &out_part_len, in, in_part_len))
341  return 0;
342  out_len += out_part_len;
343  in += in_part_len;
344  } while ((in_len -= in_part_len) > UPDATE_LENGTH_LIMIT);
345  }
346 #endif
347  if (!EVP_CipherUpdate(ctx, out ? (out + out_len) : 0,
348  &out_part_len, in, (int)in_len))
349  return 0;
350  if (out_len_ptr) *out_len_ptr = out_len += out_part_len;
351  return 1;
352 }
353 
354 /*
355  * call-seq:
356  * cipher.update(data [, buffer]) -> string or buffer
357  *
358  * Encrypts data in a streaming fashion. Hand consecutive blocks of data
359  * to the +update+ method in order to encrypt it. Returns the encrypted
360  * data chunk. When done, the output of Cipher#final should be additionally
361  * added to the result.
362  *
363  * === Parameters
364  * +data+ is a nonempty string.
365  * +buffer+ is an optional string to store the result.
366  */
367 static VALUE
369 {
370  EVP_CIPHER_CTX *ctx;
371  unsigned char *in;
372  long in_len, out_len;
373  VALUE data, str;
374 
375  rb_scan_args(argc, argv, "11", &data, &str);
376 
377  if (!RTEST(rb_attr_get(self, id_key_set)))
378  ossl_raise(eCipherError, "key not set");
379 
380  StringValue(data);
381  in = (unsigned char *)RSTRING_PTR(data);
382  if ((in_len = RSTRING_LEN(data)) == 0)
383  ossl_raise(rb_eArgError, "data must not be empty");
384  GetCipher(self, ctx);
385  out_len = in_len+EVP_CIPHER_CTX_block_size(ctx);
386  if (out_len <= 0) {
388  "data too big to make output buffer: %ld bytes", in_len);
389  }
390 
391  if (NIL_P(str)) {
392  str = rb_str_new(0, out_len);
393  } else {
394  StringValue(str);
395  rb_str_resize(str, out_len);
396  }
397 
398  if (!ossl_cipher_update_long(ctx, (unsigned char *)RSTRING_PTR(str), &out_len, in, in_len))
400  assert(out_len < RSTRING_LEN(str));
401  rb_str_set_len(str, out_len);
402 
403  return str;
404 }
405 
406 /*
407  * call-seq:
408  * cipher.final -> string
409  *
410  * Returns the remaining data held in the cipher object. Further calls to
411  * Cipher#update or Cipher#final will return garbage. This call should always
412  * be made as the last call of an encryption or decryption operation, after
413  * after having fed the entire plaintext or ciphertext to the Cipher instance.
414  *
415  * If an authenticated cipher was used, a CipherError is raised if the tag
416  * could not be authenticated successfully. Only call this method after
417  * setting the authentication tag and passing the entire contents of the
418  * ciphertext into the cipher.
419  */
420 static VALUE
422 {
423  EVP_CIPHER_CTX *ctx;
424  int out_len;
425  VALUE str;
426 
427  GetCipher(self, ctx);
428  str = rb_str_new(0, EVP_CIPHER_CTX_block_size(ctx));
429  if (!EVP_CipherFinal_ex(ctx, (unsigned char *)RSTRING_PTR(str), &out_len))
431  assert(out_len <= RSTRING_LEN(str));
432  rb_str_set_len(str, out_len);
433 
434  return str;
435 }
436 
437 /*
438  * call-seq:
439  * cipher.name -> string
440  *
441  * Returns the name of the cipher which may differ slightly from the original
442  * name provided.
443  */
444 static VALUE
446 {
447  EVP_CIPHER_CTX *ctx;
448 
449  GetCipher(self, ctx);
450 
451  return rb_str_new2(EVP_CIPHER_name(EVP_CIPHER_CTX_cipher(ctx)));
452 }
453 
454 /*
455  * call-seq:
456  * cipher.key = string -> string
457  *
458  * Sets the cipher key. To generate a key, you should either use a secure
459  * random byte string or, if the key is to be derived from a password, you
460  * should rely on PBKDF2 functionality provided by OpenSSL::PKCS5. To
461  * generate a secure random-based key, Cipher#random_key may be used.
462  *
463  * Only call this method after calling Cipher#encrypt or Cipher#decrypt.
464  */
465 static VALUE
467 {
468  EVP_CIPHER_CTX *ctx;
469 
470  StringValue(key);
471  GetCipher(self, ctx);
472 
473  if (RSTRING_LEN(key) < EVP_CIPHER_CTX_key_length(ctx))
474  ossl_raise(eCipherError, "key length too short");
475 
476  if (EVP_CipherInit_ex(ctx, NULL, NULL, (unsigned char *)RSTRING_PTR(key), NULL, -1) != 1)
478 
479  rb_ivar_set(self, id_key_set, Qtrue);
480  return key;
481 }
482 
483 /*
484  * call-seq:
485  * cipher.iv = string -> string
486  *
487  * Sets the cipher IV. Please note that since you should never be using ECB
488  * mode, an IV is always explicitly required and should be set prior to
489  * encryption. The IV itself can be safely transmitted in public, but it
490  * should be unpredictable to prevent certain kinds of attacks. You may use
491  * Cipher#random_iv to create a secure random IV.
492  *
493  * Only call this method after calling Cipher#encrypt or Cipher#decrypt.
494  *
495  * If not explicitly set, the OpenSSL default of an all-zeroes ("\\0") IV is
496  * used.
497  */
498 static VALUE
500 {
501  EVP_CIPHER_CTX *ctx;
502 
503  StringValue(iv);
504  GetCipher(self, ctx);
505 
506  if (RSTRING_LEN(iv) < EVP_CIPHER_CTX_iv_length(ctx))
507  ossl_raise(eCipherError, "iv length too short");
508 
509  if (EVP_CipherInit_ex(ctx, NULL, NULL, NULL, (unsigned char *)RSTRING_PTR(iv), -1) != 1)
511 
512  return iv;
513 }
514 
515 #ifdef HAVE_AUTHENTICATED_ENCRYPTION
516 /*
517  * call-seq:
518  * cipher.auth_data = string -> string
519  *
520  * Sets the cipher's additional authenticated data. This field must be
521  * set when using AEAD cipher modes such as GCM or CCM. If no associated
522  * data shall be used, this method must *still* be called with a value of "".
523  * The contents of this field should be non-sensitive data which will be
524  * added to the ciphertext to generate the authentication tag which validates
525  * the contents of the ciphertext.
526  *
527  * The AAD must be set prior to encryption or decryption. In encryption mode,
528  * it must be set after calling Cipher#encrypt and setting Cipher#key= and
529  * Cipher#iv=. When decrypting, the authenticated data must be set after key,
530  * iv and especially *after* the authentication tag has been set. I.e. set it
531  * only after calling Cipher#decrypt, Cipher#key=, Cipher#iv= and
532  * Cipher#auth_tag= first.
533  */
534 static VALUE
536 {
537  EVP_CIPHER_CTX *ctx;
538  unsigned char *in;
539  long in_len, out_len;
540 
541  StringValue(data);
542 
543  in = (unsigned char *) RSTRING_PTR(data);
544  in_len = RSTRING_LEN(data);
545 
546  GetCipher(self, ctx);
547 
548  if (!ossl_cipher_update_long(ctx, NULL, &out_len, in, in_len))
549  ossl_raise(eCipherError, "couldn't set additional authenticated data");
550 
551  return data;
552 }
553 
554 #define ossl_is_gcm(nid) (nid) == NID_aes_128_gcm || \
555  (nid) == NID_aes_192_gcm || \
556  (nid) == NID_aes_256_gcm
557 
558 static VALUE
559 ossl_get_gcm_auth_tag(EVP_CIPHER_CTX *ctx, int len)
560 {
561  unsigned char *tag;
562  VALUE ret;
563 
564  tag = ALLOC_N(unsigned char, len);
565 
566  if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, len, tag))
567  ossl_raise(eCipherError, "retrieving the authentication tag failed");
568 
569  ret = rb_str_new((const char *) tag, len);
570  xfree(tag);
571  return ret;
572 }
573 
574 /*
575  * call-seq:
576  * cipher.auth_tag([ tag_len ] -> string
577  *
578  * Gets the authentication tag generated by Authenticated Encryption Cipher
579  * modes (GCM for example). This tag may be stored along with the ciphertext,
580  * then set on the decryption cipher to authenticate the contents of the
581  * ciphertext against changes. If the optional integer parameter +tag_len+ is
582  * given, the returned tag will be +tag_len+ bytes long. If the parameter is
583  * omitted, the maximum length of 16 bytes will be returned. For maximum
584  * security, the default of 16 bytes should be chosen.
585  *
586  * The tag may only be retrieved after calling Cipher#final.
587  */
588 static VALUE
590 {
591  VALUE vtag_len;
592  EVP_CIPHER_CTX *ctx;
593  int nid, tag_len;
594 
595  if (rb_scan_args(argc, argv, "01", &vtag_len) == 0) {
596  tag_len = 16;
597  } else {
598  tag_len = NUM2INT(vtag_len);
599  }
600 
601  GetCipher(self, ctx);
602  nid = EVP_CIPHER_CTX_nid(ctx);
603 
604  if (ossl_is_gcm(nid)) {
605  return ossl_get_gcm_auth_tag(ctx, tag_len);
606  } else {
607  ossl_raise(eCipherError, "authentication tag not supported by this cipher");
608  return Qnil; /* dummy */
609  }
610 }
611 
612 static inline void
613 ossl_set_gcm_auth_tag(EVP_CIPHER_CTX *ctx, unsigned char *tag, int tag_len)
614 {
615  if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, tag_len, tag))
616  ossl_raise(eCipherError, "unable to set GCM tag");
617 }
618 
619 /*
620  * call-seq:
621  * cipher.auth_tag = string -> string
622  *
623  * Sets the authentication tag to verify the contents of the
624  * ciphertext. The tag must be set after calling Cipher#decrypt,
625  * Cipher#key= and Cipher#iv=, but before assigning the associated
626  * authenticated data using Cipher#auth_data= and of course, before
627  * decrypting any of the ciphertext. After all decryption is
628  * performed, the tag is verified automatically in the call to
629  * Cipher#final.
630  */
631 static VALUE
633 {
634  EVP_CIPHER_CTX *ctx;
635  int nid;
636  unsigned char *tag;
637  int tag_len;
638 
639  StringValue(vtag);
640  tag = (unsigned char *) RSTRING_PTR(vtag);
641  tag_len = RSTRING_LENINT(vtag);
642 
643  GetCipher(self, ctx);
644  nid = EVP_CIPHER_CTX_nid(ctx);
645 
646  if (ossl_is_gcm(nid)) {
647  ossl_set_gcm_auth_tag(ctx, tag, tag_len);
648  } else {
649  ossl_raise(eCipherError, "authentication tag not supported by this cipher");
650  }
651 
652  return vtag;
653 }
654 
655 /*
656  * call-seq:
657  * cipher.authenticated? -> boolean
658  *
659  * Indicated whether this Cipher instance uses an Authenticated Encryption
660  * mode.
661  */
662 static VALUE
664 {
665  EVP_CIPHER_CTX *ctx;
666  int nid;
667 
668  GetCipher(self, ctx);
669  nid = EVP_CIPHER_CTX_nid(ctx);
670 
671  if (ossl_is_gcm(nid)) {
672  return Qtrue;
673  } else {
674  return Qfalse;
675  }
676 }
677 #else
678 #define ossl_cipher_set_auth_data rb_f_notimplement
679 #define ossl_cipher_get_auth_tag rb_f_notimplement
680 #define ossl_cipher_set_auth_tag rb_f_notimplement
681 #define ossl_cipher_is_authenticated rb_f_notimplement
682 #endif
683 
684 /*
685  * call-seq:
686  * cipher.key_len = integer -> integer
687  *
688  * Sets the key length of the cipher. If the cipher is a fixed length cipher
689  * then attempting to set the key length to any value other than the fixed
690  * value is an error.
691  *
692  * Under normal circumstances you do not need to call this method (and probably shouldn't).
693  *
694  * See EVP_CIPHER_CTX_set_key_length for further information.
695  */
696 static VALUE
698 {
699  int len = NUM2INT(key_length);
700  EVP_CIPHER_CTX *ctx;
701 
702  GetCipher(self, ctx);
703  if (EVP_CIPHER_CTX_set_key_length(ctx, len) != 1)
705 
706  return key_length;
707 }
708 
709 #if defined(HAVE_EVP_CIPHER_CTX_SET_PADDING)
710 /*
711  * call-seq:
712  * cipher.padding = integer -> integer
713  *
714  * Enables or disables padding. By default encryption operations are padded using standard block padding and the
715  * padding is checked and removed when decrypting. If the pad parameter is zero then no padding is performed, the
716  * total amount of data encrypted or decrypted must then be a multiple of the block size or an error will occur.
717  *
718  * See EVP_CIPHER_CTX_set_padding for further information.
719  */
720 static VALUE
721 ossl_cipher_set_padding(VALUE self, VALUE padding)
722 {
723  EVP_CIPHER_CTX *ctx;
724  int pad = NUM2INT(padding);
725 
726  GetCipher(self, ctx);
727  if (EVP_CIPHER_CTX_set_padding(ctx, pad) != 1)
729  return padding;
730 }
731 #else
732 #define ossl_cipher_set_padding rb_f_notimplement
733 #endif
734 
735 #define CIPHER_0ARG_INT(func) \
736  static VALUE \
737  ossl_cipher_##func(VALUE self) \
738  { \
739  EVP_CIPHER_CTX *ctx; \
740  GetCipher(self, ctx); \
741  return INT2NUM(EVP_CIPHER_##func(EVP_CIPHER_CTX_cipher(ctx))); \
742  }
743 
744 /*
745  * call-seq:
746  * cipher.key_len -> integer
747  *
748  * Returns the key length in bytes of the Cipher.
749  */
750 CIPHER_0ARG_INT(key_length)
751 /*
752  * call-seq:
753  * cipher.iv_len -> integer
754  *
755  * Returns the expected length in bytes for an IV for this Cipher.
756  */
757 CIPHER_0ARG_INT(iv_length)
758 /*
759  * call-seq:
760  * cipher.block_size -> integer
761  *
762  * Returns the size in bytes of the blocks on which this Cipher operates on.
763  */
764 CIPHER_0ARG_INT(block_size)
765 
766 /*
767  * INIT
768  */
769 void
771 {
772 #if 0
773  mOSSL = rb_define_module("OpenSSL"); /* let rdoc know about mOSSL */
774 #endif
775 
776  /* Document-class: OpenSSL::Cipher
777  *
778  * Provides symmetric algorithms for encryption and decryption. The
779  * algorithms that are available depend on the particular version
780  * of OpenSSL that is installed.
781  *
782  * === Listing all supported algorithms
783  *
784  * A list of supported algorithms can be obtained by
785  *
786  * puts OpenSSL::Cipher.ciphers
787  *
788  * === Instantiating a Cipher
789  *
790  * There are several ways to create a Cipher instance. Generally, a
791  * Cipher algorithm is categorized by its name, the key length in bits
792  * and the cipher mode to be used. The most generic way to create a
793  * Cipher is the following
794  *
795  * cipher = OpenSSL::Cipher.new('<name>-<key length>-<mode>')
796  *
797  * That is, a string consisting of the hyphenated concatenation of the
798  * individual components name, key length and mode. Either all uppercase
799  * or all lowercase strings may be used, for example:
800  *
801  * cipher = OpenSSL::Cipher.new('AES-128-CBC')
802  *
803  * For each algorithm supported, there is a class defined under the
804  * Cipher class that goes by the name of the cipher, e.g. to obtain an
805  * instance of AES, you could also use
806  *
807  * # these are equivalent
808  * cipher = OpenSSL::Cipher::AES.new(128, :CBC)
809  * cipher = OpenSSL::Cipher::AES.new(128, 'CBC')
810  * cipher = OpenSSL::Cipher::AES.new('128-CBC')
811  *
812  * Finally, due to its wide-spread use, there are also extra classes
813  * defined for the different key sizes of AES
814  *
815  * cipher = OpenSSL::Cipher::AES128.new(:CBC)
816  * cipher = OpenSSL::Cipher::AES192.new(:CBC)
817  * cipher = OpenSSL::Cipher::AES256.new(:CBC)
818  *
819  * === Choosing either encryption or decryption mode
820  *
821  * Encryption and decryption are often very similar operations for
822  * symmetric algorithms, this is reflected by not having to choose
823  * different classes for either operation, both can be done using the
824  * same class. Still, after obtaining a Cipher instance, we need to
825  * tell the instance what it is that we intend to do with it, so we
826  * need to call either
827  *
828  * cipher.encrypt
829  *
830  * or
831  *
832  * cipher.decrypt
833  *
834  * on the Cipher instance. This should be the first call after creating
835  * the instance, otherwise configuration that has already been set could
836  * get lost in the process.
837  *
838  * === Choosing a key
839  *
840  * Symmetric encryption requires a key that is the same for the encrypting
841  * and for the decrypting party and after initial key establishment should
842  * be kept as private information. There are a lot of ways to create
843  * insecure keys, the most notable is to simply take a password as the key
844  * without processing the password further. A simple and secure way to
845  * create a key for a particular Cipher is
846  *
847  * cipher = OpenSSL::AES256.new(:CFB)
848  * cipher.encrypt
849  * key = cipher.random_key # also sets the generated key on the Cipher
850  *
851  * If you absolutely need to use passwords as encryption keys, you
852  * should use Password-Based Key Derivation Function 2 (PBKDF2) by
853  * generating the key with the help of the functionality provided by
854  * OpenSSL::PKCS5.pbkdf2_hmac_sha1 or OpenSSL::PKCS5.pbkdf2_hmac.
855  *
856  * Although there is Cipher#pkcs5_keyivgen, its use is deprecated and
857  * it should only be used in legacy applications because it does not use
858  * the newer PKCS#5 v2 algorithms.
859  *
860  * === Choosing an IV
861  *
862  * The cipher modes CBC, CFB, OFB and CTR all need an "initialization
863  * vector", or short, IV. ECB mode is the only mode that does not require
864  * an IV, but there is almost no legitimate use case for this mode
865  * because of the fact that it does not sufficiently hide plaintext
866  * patterns. Therefore
867  *
868  * <b>You should never use ECB mode unless you are absolutely sure that
869  * you absolutely need it</b>
870  *
871  * Because of this, you will end up with a mode that explicitly requires
872  * an IV in any case. Note that for backwards compatibility reasons,
873  * setting an IV is not explicitly mandated by the Cipher API. If not
874  * set, OpenSSL itself defaults to an all-zeroes IV ("\\0", not the
875  * character). Although the IV can be seen as public information, i.e.
876  * it may be transmitted in public once generated, it should still stay
877  * unpredictable to prevent certain kinds of attacks. Therefore, ideally
878  *
879  * <b>Always create a secure random IV for every encryption of your
880  * Cipher</b>
881  *
882  * A new, random IV should be created for every encryption of data. Think
883  * of the IV as a nonce (number used once) - it's public but random and
884  * unpredictable. A secure random IV can be created as follows
885  *
886  * cipher = ...
887  * cipher.encrypt
888  * key = cipher.random_key
889  * iv = cipher.random_iv # also sets the generated IV on the Cipher
890  *
891  * Although the key is generally a random value, too, it is a bad choice
892  * as an IV. There are elaborate ways how an attacker can take advantage
893  * of such an IV. As a general rule of thumb, exposing the key directly
894  * or indirectly should be avoided at all cost and exceptions only be
895  * made with good reason.
896  *
897  * === Calling Cipher#final
898  *
899  * ECB (which should not be used) and CBC are both block-based modes.
900  * This means that unlike for the other streaming-based modes, they
901  * operate on fixed-size blocks of data, and therefore they require a
902  * "finalization" step to produce or correctly decrypt the last block of
903  * data by appropriately handling some form of padding. Therefore it is
904  * essential to add the output of OpenSSL::Cipher#final to your
905  * encryption/decryption buffer or you will end up with decryption errors
906  * or truncated data.
907  *
908  * Although this is not really necessary for streaming-mode ciphers, it is
909  * still recommended to apply the same pattern of adding the output of
910  * Cipher#final there as well - it also enables you to switch between
911  * modes more easily in the future.
912  *
913  * === Encrypting and decrypting some data
914  *
915  * data = "Very, very confidential data"
916  *
917  * cipher = OpenSSL::Cipher::AES.new(128, :CBC)
918  * cipher.encrypt
919  * key = cipher.random_key
920  * iv = cipher.random_iv
921  *
922  * encrypted = cipher.update(data) + cipher.final
923  * ...
924  * decipher = OpenSSL::Cipher::AES.new(128, :CBC)
925  * decipher.decrypt
926  * decipher.key = key
927  * decipher.iv = iv
928  *
929  * plain = decipher.update(encrypted) + decipher.final
930  *
931  * puts data == plain #=> true
932  *
933  * === Authenticated Encryption and Associated Data (AEAD)
934  *
935  * If the OpenSSL version used supports it, an Authenticated Encryption
936  * mode (such as GCM or CCM) should always be preferred over any
937  * unauthenticated mode. Currently, OpenSSL supports AE only in combination
938  * with Associated Data (AEAD) where additional associated data is included
939  * in the encryption process to compute a tag at the end of the encryption.
940  * This tag will also be used in the decryption process and by verifying
941  * its validity, the authenticity of a given ciphertext is established.
942  *
943  * This is superior to unauthenticated modes in that it allows to detect
944  * if somebody effectively changed the ciphertext after it had been
945  * encrypted. This prevents malicious modifications of the ciphertext that
946  * could otherwise be exploited to modify ciphertexts in ways beneficial to
947  * potential attackers.
948  *
949  * If no associated data is needed for encryption and later decryption,
950  * the OpenSSL library still requires a value to be set - "" may be used in
951  * case none is available. An example using the GCM (Galois Counter Mode):
952  *
953  * cipher = OpenSSL::Cipher::AES.new(128, :GCM)
954  * cipher.encrypt
955  * key = cipher.random_key
956  * iv = cipher.random_iv
957  * cipher.auth_data = ""
958  *
959  * encrypted = cipher.update(data) + cipher.final
960  * tag = cipher.auth_tag
961  *
962  * decipher = OpenSSL::Cipher::AES.new(128, :GCM)
963  * decipher.decrypt
964  * decipher.key = key
965  * decipher.iv = iv
966  * decipher.auth_tag = tag
967  * decipher.auth_data = ""
968  *
969  * plain = decipher.update(encrypted) + decipher.final
970  *
971  * puts data == plain #=> true
972  */
975 
983  rb_define_method(cCipher, "pkcs5_keyivgen", ossl_cipher_pkcs5_keyivgen, -1);
993  rb_define_method(cCipher, "key_len", ossl_cipher_key_length, 0);
995  rb_define_method(cCipher, "iv_len", ossl_cipher_iv_length, 0);
996  rb_define_method(cCipher, "block_size", ossl_cipher_block_size, 0);
998 
999  id_key_set = rb_intern_const("key_set");
1000 }
1001 
static VALUE ossl_cipher_alloc(VALUE klass)
Definition: ossl_cipher.c:83
#define ossl_cipher_set_auth_data
Definition: ossl_cipher.c:678
VALUE mOSSL
Definition: ossl.c:259
static VALUE ossl_cipher_final(VALUE self)
Definition: ossl_cipher.c:421
#define ossl_cipher_set_padding
Definition: ossl_cipher.c:732
#define NUM2INT(x)
Definition: ruby.h:622
#define OPENSSL_cleanse(p, l)
static VALUE ossl_cipher_init(int argc, VALUE *argv, VALUE self, int mode)
Definition: ossl_cipher.c:196
#define Qtrue
Definition: ruby.h:434
#define AllocCipher(obj, ctx)
Definition: ossl_cipher.c:17
VALUE rb_ary_push(VALUE ary, VALUE item)
Definition: array.c:822
static VALUE ossl_cipher_update(int argc, VALUE *argv, VALUE self)
Definition: ossl_cipher.c:368
void rb_str_set_len(VALUE, long)
Definition: string.c:1838
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition: class.c:534
void rb_define_alloc_func(VALUE, rb_alloc_func_t)
#define EVP_CipherFinal_ex(ctx, outm, outl)
#define GetCipher(obj, ctx)
Definition: ossl_cipher.c:22
VALUE rb_eRangeError
Definition: error.c:520
#define WrapCipher(obj, klass, ctx)
Definition: ossl_cipher.c:13
static VALUE ossl_cipher_set_key_length(VALUE self, VALUE key_length)
Definition: ossl_cipher.c:697
#define rb_define_copy_func(klass, func)
Definition: ruby_missing.h:14
static VALUE ossl_cipher_initialize(VALUE self, VALUE str)
Definition: ossl_cipher.c:101
VALUE ossl_cipher_new(const EVP_CIPHER *cipher)
Definition: ossl_cipher.c:56
VALUE eCipherError
Definition: ossl_cipher.c:37
#define ALLOC_N(type, n)
Definition: ruby.h:1223
#define CIPHER_0ARG_INT(func)
Definition: ossl_cipher.c:735
#define SafeGetCipher(obj, ctx)
Definition: ossl_cipher.c:28
RUBY_EXTERN VALUE rb_cObject
Definition: ruby.h:1426
VALUE rb_eRuntimeError
Definition: error.c:515
#define EVP_CipherInit_ex(ctx, type, impl, key, iv, enc)
#define ossl_cipher_get_auth_tag
Definition: ossl_cipher.c:679
#define EVP_CIPHER_name(e)
VALUE rb_ary_new(void)
Definition: array.c:424
#define NIL_P(v)
Definition: ruby.h:446
const EVP_MD * GetDigestPtr(VALUE obj)
Definition: ossl_digest.c:36
VALUE eOSSLError
Definition: ossl.c:264
int argc
Definition: ruby.c:130
#define Qfalse
Definition: ruby.h:433
const EVP_CIPHER * GetCipherPtr(VALUE obj)
Definition: ossl_cipher.c:46
static ID id_key_set
Definition: ossl_cipher.c:38
VALUE rb_str_resize(VALUE, long)
Definition: string.c:1854
#define RSTRING_LEN(str)
Definition: ruby.h:862
void rb_define_module_function(VALUE module, const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a module function for module.
Definition: class.c:1512
static VALUE ossl_cipher_encrypt(int argc, VALUE *argv, VALUE self)
Definition: ossl_cipher.c:253
static int ossl_cipher_update_long(EVP_CIPHER_CTX *ctx, unsigned char *out, long *out_len_ptr, const unsigned char *in, long in_len)
Definition: ossl_cipher.c:328
VALUE rb_class_path(VALUE)
Definition: variable.c:261
void ruby_xfree(void *x)
Definition: gc.c:3653
#define ossl_s_ciphers
Definition: ossl_cipher.c:171
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Definition: class.c:1570
VALUE rb_ivar_set(VALUE, ID, VALUE)
Definition: variable.c:1128
#define PRIsVALUE
Definition: ruby.h:147
unsigned long ID
Definition: ruby.h:105
static VALUE ossl_cipher_copy(VALUE self, VALUE other)
Definition: ossl_cipher.c:124
#define Qnil
Definition: ruby.h:435
static VALUE ossl_cipher_decrypt(int argc, VALUE *argv, VALUE self)
Definition: ossl_cipher.c:271
unsigned long VALUE
Definition: ruby.h:104
#define ossl_cipher_set_auth_tag
Definition: ossl_cipher.c:680
#define GetCipherInit(obj, ctx)
Definition: ossl_cipher.c:19
void xfree(void *)
static VALUE ossl_cipher_pkcs5_keyivgen(int argc, VALUE *argv, VALUE self)
Definition: ossl_cipher.c:297
#define RSTRING_PTR(str)
Definition: ruby.h:866
#define UPDATE_LENGTH_LIMIT
uint8_t key[16]
Definition: random.c:1370
#define RTEST(v)
Definition: ruby.h:445
void ossl_raise(VALUE exc, const char *fmt,...)
Definition: ossl.c:333
static VALUE ossl_cipher_reset(VALUE self)
Definition: ossl_cipher.c:184
#define assert(condition)
Definition: ossl.h:45
const char * name
Definition: nkf.c:208
#define StringValuePtr(v)
Definition: ruby.h:547
void Init_ossl_cipher(void)
Definition: ossl_cipher.c:770
#define RSTRING_LENINT(str)
Definition: ruby.h:874
#define rb_check_frozen(obj)
Definition: intern.h:258
#define rb_intern_const(str)
Definition: ruby.h:1332
VALUE rb_define_module(const char *name)
Definition: class.c:606
VALUE cCipher
Definition: ossl_cipher.c:36
int EVP_CIPHER_CTX_copy(EVP_CIPHER_CTX *out, EVP_CIPHER_CTX *in)
static VALUE ossl_cipher_set_key(VALUE self, VALUE key)
Definition: ossl_cipher.c:466
static VALUE ossl_cipher_name(VALUE self)
Definition: ossl_cipher.c:445
#define NULL
Definition: _sdbm.c:102
void rb_define_method(VALUE klass, const char *name, VALUE(*func)(ANYARGS), int argc)
Definition: class.c:1344
VALUE rb_str_new2(const char *)
void rb_warn(const char *fmt,...)
Definition: error.c:221
static VALUE ossl_cipher_set_iv(VALUE self, VALUE iv)
Definition: ossl_cipher.c:499
VALUE rb_eArgError
Definition: error.c:517
#define ossl_cipher_is_authenticated
Definition: ossl_cipher.c:681
static void ossl_cipher_free(EVP_CIPHER_CTX *ctx)
Definition: ossl_cipher.c:74
VALUE rb_attr_get(VALUE, ID)
Definition: variable.c:1122
char ** argv
Definition: ruby.c:131
#define StringValue(v)
Definition: ruby.h:546
VALUE rb_str_new(const char *, long)
Definition: string.c:425
VALUE rb_obj_class(VALUE)
Definition: object.c:194