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