1/* 2 * $Id: ossl_cipher.c 44659 2014-01-19 16:28:53Z nagachika $ 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 */ 36VALUE cCipher; 37VALUE eCipherError; 38 39static VALUE ossl_cipher_alloc(VALUE klass); 40 41/* 42 * PUBLIC 43 */ 44const EVP_CIPHER * 45GetCipherPtr(VALUE obj) 46{ 47 EVP_CIPHER_CTX *ctx; 48 49 SafeGetCipher(obj, ctx); 50 51 return EVP_CIPHER_CTX_cipher(ctx); 52} 53 54VALUE 55ossl_cipher_new(const EVP_CIPHER *cipher) 56{ 57 VALUE ret; 58 EVP_CIPHER_CTX *ctx; 59 60 ret = ossl_cipher_alloc(cCipher); 61 AllocCipher(ret, ctx); 62 EVP_CIPHER_CTX_init(ctx); 63 if (EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, -1) != 1) 64 ossl_raise(eCipherError, NULL); 65 66 return ret; 67} 68 69/* 70 * PRIVATE 71 */ 72static void 73ossl_cipher_free(EVP_CIPHER_CTX *ctx) 74{ 75 if (ctx) { 76 EVP_CIPHER_CTX_cleanup(ctx); 77 ruby_xfree(ctx); 78 } 79} 80 81static VALUE 82ossl_cipher_alloc(VALUE klass) 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 */ 99static VALUE 100ossl_cipher_initialize(VALUE self, VALUE str) 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) 125 ossl_raise(eCipherError, NULL); 126 127 return self; 128} 129 130static VALUE 131ossl_cipher_copy(VALUE self, VALUE other) 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) 144 ossl_raise(eCipherError, NULL); 145 146 return self; 147} 148 149#ifdef HAVE_OBJ_NAME_DO_ALL_SORTED 150static void* 151add_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 */ 165static VALUE 166ossl_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 */ 190static VALUE 191ossl_cipher_reset(VALUE self) 192{ 193 EVP_CIPHER_CTX *ctx; 194 195 GetCipher(self, ctx); 196 if (EVP_CipherInit_ex(ctx, NULL, NULL, NULL, NULL, -1) != 1) 197 ossl_raise(eCipherError, NULL); 198 199 return self; 200} 201 202static VALUE 203ossl_cipher_init(int argc, VALUE *argv, VALUE self, int mode) 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) { 240 ossl_raise(eCipherError, NULL); 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 */ 258static VALUE 259ossl_cipher_encrypt(int argc, VALUE *argv, VALUE self) 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 */ 276static VALUE 277ossl_cipher_decrypt(int argc, VALUE *argv, VALUE self) 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 */ 302static VALUE 303ossl_cipher_pkcs5_keyivgen(int argc, VALUE *argv, VALUE self) 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) 325 ossl_raise(eCipherError, NULL); 326 OPENSSL_cleanse(key, sizeof key); 327 OPENSSL_cleanse(iv, sizeof iv); 328 329 return Qnil; 330} 331 332/* 333 * call-seq: 334 * cipher.update(data [, buffer]) -> string or buffer 335 * 336 * Encrypts data in a streaming fashion. Hand consecutive blocks of data 337 * to the +update+ method in order to encrypt it. Returns the encrypted 338 * data chunk. When done, the output of Cipher#final should be additionally 339 * added to the result. 340 * 341 * === Parameters 342 * +data+ is a nonempty string. 343 * +buffer+ is an optional string to store the result. 344 */ 345static VALUE 346ossl_cipher_update(int argc, VALUE *argv, VALUE self) 347{ 348 EVP_CIPHER_CTX *ctx; 349 unsigned char *in; 350 int in_len, out_len; 351 VALUE data, str; 352 353 rb_scan_args(argc, argv, "11", &data, &str); 354 355 StringValue(data); 356 in = (unsigned char *)RSTRING_PTR(data); 357 if ((in_len = RSTRING_LENINT(data)) == 0) 358 ossl_raise(rb_eArgError, "data must not be empty"); 359 GetCipher(self, ctx); 360 out_len = in_len+EVP_CIPHER_CTX_block_size(ctx); 361 362 if (NIL_P(str)) { 363 str = rb_str_new(0, out_len); 364 } else { 365 StringValue(str); 366 rb_str_resize(str, out_len); 367 } 368 369 if (!EVP_CipherUpdate(ctx, (unsigned char *)RSTRING_PTR(str), &out_len, in, in_len)) 370 ossl_raise(eCipherError, NULL); 371 assert(out_len < RSTRING_LEN(str)); 372 rb_str_set_len(str, out_len); 373 374 return str; 375} 376 377/* 378 * call-seq: 379 * cipher.final -> string 380 * 381 * Returns the remaining data held in the cipher object. Further calls to 382 * Cipher#update or Cipher#final will return garbage. This call should always 383 * be made as the last call of an encryption or decryption operation, after 384 * after having fed the entire plaintext or ciphertext to the Cipher instance. 385 * 386 * If an authenticated cipher was used, a CipherError is raised if the tag 387 * could not be authenticated successfully. Only call this method after 388 * setting the authentication tag and passing the entire contents of the 389 * ciphertext into the cipher. 390 */ 391static VALUE 392ossl_cipher_final(VALUE self) 393{ 394 EVP_CIPHER_CTX *ctx; 395 int out_len; 396 VALUE str; 397 398 GetCipher(self, ctx); 399 str = rb_str_new(0, EVP_CIPHER_CTX_block_size(ctx)); 400 if (!EVP_CipherFinal_ex(ctx, (unsigned char *)RSTRING_PTR(str), &out_len)) 401 ossl_raise(eCipherError, NULL); 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.name -> string 411 * 412 * Returns the name of the cipher which may differ slightly from the original 413 * name provided. 414 */ 415static VALUE 416ossl_cipher_name(VALUE self) 417{ 418 EVP_CIPHER_CTX *ctx; 419 420 GetCipher(self, ctx); 421 422 return rb_str_new2(EVP_CIPHER_name(EVP_CIPHER_CTX_cipher(ctx))); 423} 424 425/* 426 * call-seq: 427 * cipher.key = string -> string 428 * 429 * Sets the cipher key. To generate a key, you should either use a secure 430 * random byte string or, if the key is to be derived from a password, you 431 * should rely on PBKDF2 functionality provided by OpenSSL::PKCS5. To 432 * generate a secure random-based key, Cipher#random_key may be used. 433 * 434 * Only call this method after calling Cipher#encrypt or Cipher#decrypt. 435 */ 436static VALUE 437ossl_cipher_set_key(VALUE self, VALUE key) 438{ 439 EVP_CIPHER_CTX *ctx; 440 441 StringValue(key); 442 GetCipher(self, ctx); 443 444 if (RSTRING_LEN(key) < EVP_CIPHER_CTX_key_length(ctx)) 445 ossl_raise(eCipherError, "key length too short"); 446 447 if (EVP_CipherInit_ex(ctx, NULL, NULL, (unsigned char *)RSTRING_PTR(key), NULL, -1) != 1) 448 ossl_raise(eCipherError, NULL); 449 450 return key; 451} 452 453/* 454 * call-seq: 455 * cipher.iv = string -> string 456 * 457 * Sets the cipher IV. Please note that since you should never be using ECB 458 * mode, an IV is always explicitly required and should be set prior to 459 * encryption. The IV itself can be safely transmitted in public, but it 460 * should be unpredictable to prevent certain kinds of attacks. You may use 461 * Cipher#random_iv to create a secure random IV. 462 * 463 * Only call this method after calling Cipher#encrypt or Cipher#decrypt. 464 * 465 * If not explicitly set, the OpenSSL default of an all-zeroes ("\\0") IV is 466 * used. 467 */ 468static VALUE 469ossl_cipher_set_iv(VALUE self, VALUE iv) 470{ 471 EVP_CIPHER_CTX *ctx; 472 473 StringValue(iv); 474 GetCipher(self, ctx); 475 476 if (RSTRING_LEN(iv) < EVP_CIPHER_CTX_iv_length(ctx)) 477 ossl_raise(eCipherError, "iv length too short"); 478 479 if (EVP_CipherInit_ex(ctx, NULL, NULL, NULL, (unsigned char *)RSTRING_PTR(iv), -1) != 1) 480 ossl_raise(eCipherError, NULL); 481 482 return iv; 483} 484 485#ifdef HAVE_AUTHENTICATED_ENCRYPTION 486/* 487 * call-seq: 488 * cipher.auth_data = string -> string 489 * 490 * Sets the cipher's additional authenticated data. This field must be 491 * set when using AEAD cipher modes such as GCM or CCM. If no associated 492 * data shall be used, this method must *still* be called with a value of "". 493 * The contents of this field should be non-sensitive data which will be 494 * added to the ciphertext to generate the authentication tag which validates 495 * the contents of the ciphertext. 496 * 497 * The AAD must be set prior to encryption or decryption. In encryption mode, 498 * it must be set after calling Cipher#encrypt and setting Cipher#key= and 499 * Cipher#iv=. When decrypting, the authenticated data must be set after key, 500 * iv and especially *after* the authentication tag has been set. I.e. set it 501 * only after calling Cipher#decrypt, Cipher#key=, Cipher#iv= and 502 * Cipher#auth_tag= first. 503 */ 504static VALUE 505ossl_cipher_set_auth_data(VALUE self, VALUE data) 506{ 507 EVP_CIPHER_CTX *ctx; 508 unsigned char *in; 509 int in_len; 510 int out_len; 511 512 StringValue(data); 513 514 in = (unsigned char *) RSTRING_PTR(data); 515 in_len = RSTRING_LENINT(data); 516 517 GetCipher(self, ctx); 518 519 if (!EVP_CipherUpdate(ctx, NULL, &out_len, in, in_len)) 520 ossl_raise(eCipherError, "couldn't set additional authenticated data"); 521 522 return data; 523} 524 525#define ossl_is_gcm(nid) (nid) == NID_aes_128_gcm || \ 526 (nid) == NID_aes_192_gcm || \ 527 (nid) == NID_aes_256_gcm 528 529static VALUE 530ossl_get_gcm_auth_tag(EVP_CIPHER_CTX *ctx, int len) 531{ 532 unsigned char *tag; 533 VALUE ret; 534 535 tag = ALLOC_N(unsigned char, len); 536 537 if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, len, tag)) 538 ossl_raise(eCipherError, "retrieving the authentication tag failed"); 539 540 ret = rb_str_new((const char *) tag, len); 541 xfree(tag); 542 return ret; 543} 544 545/* 546 * call-seq: 547 * cipher.auth_tag([ tag_len ] -> string 548 * 549 * Gets the authentication tag generated by Authenticated Encryption Cipher 550 * modes (GCM for example). This tag may be stored along with the ciphertext, 551 * then set on the decryption cipher to authenticate the contents of the 552 * ciphertext against changes. If the optional integer parameter +tag_len+ is 553 * given, the returned tag will be +tag_len+ bytes long. If the parameter is 554 * omitted, the maximum length of 16 bytes will be returned. For maximum 555 * security, the default of 16 bytes should be chosen. 556 * 557 * The tag may only be retrieved after calling Cipher#final. 558 */ 559static VALUE 560ossl_cipher_get_auth_tag(int argc, VALUE *argv, VALUE self) 561{ 562 VALUE vtag_len; 563 EVP_CIPHER_CTX *ctx; 564 int nid, tag_len; 565 566 if (rb_scan_args(argc, argv, "01", &vtag_len) == 0) { 567 tag_len = 16; 568 } else { 569 tag_len = NUM2INT(vtag_len); 570 } 571 572 GetCipher(self, ctx); 573 nid = EVP_CIPHER_CTX_nid(ctx); 574 575 if (ossl_is_gcm(nid)) { 576 return ossl_get_gcm_auth_tag(ctx, tag_len); 577 } else { 578 ossl_raise(eCipherError, "authentication tag not supported by this cipher"); 579 return Qnil; /* dummy */ 580 } 581} 582 583static inline void 584ossl_set_gcm_auth_tag(EVP_CIPHER_CTX *ctx, unsigned char *tag, int tag_len) 585{ 586 if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, tag_len, tag)) 587 ossl_raise(eCipherError, "unable to set GCM tag"); 588} 589 590/* 591 * call-seq: 592 * cipher.auth_tag = string -> string 593 * 594 * Sets the authentication tag to verify the contents of the 595 * ciphertext. The tag must be set after calling Cipher#decrypt, 596 * Cipher#key= and Cipher#iv=, but before assigning the associated 597 * authenticated data using Cipher#auth_data= and of course, before 598 * decrypting any of the ciphertext. After all decryption is 599 * performed, the tag is verified automatically in the call to 600 * Cipher#final. 601 */ 602static VALUE 603ossl_cipher_set_auth_tag(VALUE self, VALUE vtag) 604{ 605 EVP_CIPHER_CTX *ctx; 606 int nid; 607 unsigned char *tag; 608 int tag_len; 609 610 StringValue(vtag); 611 tag = (unsigned char *) RSTRING_PTR(vtag); 612 tag_len = RSTRING_LENINT(vtag); 613 614 GetCipher(self, ctx); 615 nid = EVP_CIPHER_CTX_nid(ctx); 616 617 if (ossl_is_gcm(nid)) { 618 ossl_set_gcm_auth_tag(ctx, tag, tag_len); 619 } else { 620 ossl_raise(eCipherError, "authentication tag not supported by this cipher"); 621 } 622 623 return vtag; 624} 625 626/* 627 * call-seq: 628 * cipher.authenticated? -> boolean 629 * 630 * Indicated whether this Cipher instance uses an Authenticated Encryption 631 * mode. 632 */ 633static VALUE 634ossl_cipher_is_authenticated(VALUE self) 635{ 636 EVP_CIPHER_CTX *ctx; 637 int nid; 638 639 GetCipher(self, ctx); 640 nid = EVP_CIPHER_CTX_nid(ctx); 641 642 if (ossl_is_gcm(nid)) { 643 return Qtrue; 644 } else { 645 return Qfalse; 646 } 647} 648#else 649#define ossl_cipher_set_auth_data rb_f_notimplement 650#define ossl_cipher_get_auth_tag rb_f_notimplement 651#define ossl_cipher_set_auth_tag rb_f_notimplement 652#define ossl_cipher_is_authenticated rb_f_notimplement 653#endif 654 655/* 656 * call-seq: 657 * cipher.key_len = integer -> integer 658 * 659 * Sets the key length of the cipher. If the cipher is a fixed length cipher 660 * then attempting to set the key length to any value other than the fixed 661 * value is an error. 662 * 663 * Under normal circumstances you do not need to call this method (and probably shouldn't). 664 * 665 * See EVP_CIPHER_CTX_set_key_length for further information. 666 */ 667static VALUE 668ossl_cipher_set_key_length(VALUE self, VALUE key_length) 669{ 670 int len = NUM2INT(key_length); 671 EVP_CIPHER_CTX *ctx; 672 673 GetCipher(self, ctx); 674 if (EVP_CIPHER_CTX_set_key_length(ctx, len) != 1) 675 ossl_raise(eCipherError, NULL); 676 677 return key_length; 678} 679 680#if defined(HAVE_EVP_CIPHER_CTX_SET_PADDING) 681/* 682 * call-seq: 683 * cipher.padding = integer -> integer 684 * 685 * Enables or disables padding. By default encryption operations are padded using standard block padding and the 686 * padding is checked and removed when decrypting. If the pad parameter is zero then no padding is performed, the 687 * total amount of data encrypted or decrypted must then be a multiple of the block size or an error will occur. 688 * 689 * See EVP_CIPHER_CTX_set_padding for further information. 690 */ 691static VALUE 692ossl_cipher_set_padding(VALUE self, VALUE padding) 693{ 694 EVP_CIPHER_CTX *ctx; 695 int pad = NUM2INT(padding); 696 697 GetCipher(self, ctx); 698 if (EVP_CIPHER_CTX_set_padding(ctx, pad) != 1) 699 ossl_raise(eCipherError, NULL); 700 return padding; 701} 702#else 703#define ossl_cipher_set_padding rb_f_notimplement 704#endif 705 706#define CIPHER_0ARG_INT(func) \ 707 static VALUE \ 708 ossl_cipher_##func(VALUE self) \ 709 { \ 710 EVP_CIPHER_CTX *ctx; \ 711 GetCipher(self, ctx); \ 712 return INT2NUM(EVP_CIPHER_##func(EVP_CIPHER_CTX_cipher(ctx))); \ 713 } 714 715/* 716 * call-seq: 717 * cipher.key_len -> integer 718 * 719 * Returns the key length in bytes of the Cipher. 720 */ 721CIPHER_0ARG_INT(key_length) 722/* 723 * call-seq: 724 * cipher.iv_len -> integer 725 * 726 * Returns the expected length in bytes for an IV for this Cipher. 727 */ 728CIPHER_0ARG_INT(iv_length) 729/* 730 * call-seq: 731 * cipher.block_size -> integer 732 * 733 * Returns the size in bytes of the blocks on which this Cipher operates on. 734 */ 735CIPHER_0ARG_INT(block_size) 736 737/* 738 * INIT 739 */ 740void 741Init_ossl_cipher(void) 742{ 743#if 0 744 mOSSL = rb_define_module("OpenSSL"); /* let rdoc know about mOSSL */ 745#endif 746 747 /* Document-class: OpenSSL::Cipher 748 * 749 * Provides symmetric algorithms for encryption and decryption. The 750 * algorithms that are available depend on the particular version 751 * of OpenSSL that is installed. 752 * 753 * === Listing all supported algorithms 754 * 755 * A list of supported algorithms can be obtained by 756 * 757 * puts OpenSSL::Cipher.ciphers 758 * 759 * === Instantiating a Cipher 760 * 761 * There are several ways to create a Cipher instance. Generally, a 762 * Cipher algorithm is categorized by its name, the key length in bits 763 * and the cipher mode to be used. The most generic way to create a 764 * Cipher is the following 765 * 766 * cipher = OpenSSL::Cipher.new('<name>-<key length>-<mode>') 767 * 768 * That is, a string consisting of the hyphenated concatenation of the 769 * individual components name, key length and mode. Either all uppercase 770 * or all lowercase strings may be used, for example: 771 * 772 * cipher = OpenSSL::Cipher.new('AES-128-CBC') 773 * 774 * For each algorithm supported, there is a class defined under the 775 * Cipher class that goes by the name of the cipher, e.g. to obtain an 776 * instance of AES, you could also use 777 * 778 * # these are equivalent 779 * cipher = OpenSSL::Cipher::AES.new(128, :CBC) 780 * cipher = OpenSSL::Cipher::AES.new(128, 'CBC') 781 * cipher = OpenSSL::Cipher::AES.new('128-CBC') 782 * 783 * Finally, due to its wide-spread use, there are also extra classes 784 * defined for the different key sizes of AES 785 * 786 * cipher = OpenSSL::Cipher::AES128.new(:CBC) 787 * cipher = OpenSSL::Cipher::AES192.new(:CBC) 788 * cipher = OpenSSL::Cipher::AES256.new(:CBC) 789 * 790 * === Choosing either encryption or decryption mode 791 * 792 * Encryption and decryption are often very similar operations for 793 * symmetric algorithms, this is reflected by not having to choose 794 * different classes for either operation, both can be done using the 795 * same class. Still, after obtaining a Cipher instance, we need to 796 * tell the instance what it is that we intend to do with it, so we 797 * need to call either 798 * 799 * cipher.encrypt 800 * 801 * or 802 * 803 * cipher.decrypt 804 * 805 * on the Cipher instance. This should be the first call after creating 806 * the instance, otherwise configuration that has already been set could 807 * get lost in the process. 808 * 809 * === Choosing a key 810 * 811 * Symmetric encryption requires a key that is the same for the encrypting 812 * and for the decrypting party and after initial key establishment should 813 * be kept as private information. There are a lot of ways to create 814 * insecure keys, the most notable is to simply take a password as the key 815 * without processing the password further. A simple and secure way to 816 * create a key for a particular Cipher is 817 * 818 * cipher = OpenSSL::AES256.new(:CFB) 819 * cipher.encrypt 820 * key = cipher.random_key # also sets the generated key on the Cipher 821 * 822 * If you absolutely need to use passwords as encryption keys, you 823 * should use Password-Based Key Derivation Function 2 (PBKDF2) by 824 * generating the key with the help of the functionality provided by 825 * OpenSSL::PKCS5.pbkdf2_hmac_sha1 or OpenSSL::PKCS5.pbkdf2_hmac. 826 * 827 * Although there is Cipher#pkcs5_keyivgen, its use is deprecated and 828 * it should only be used in legacy applications because it does not use 829 * the newer PKCS#5 v2 algorithms. 830 * 831 * === Choosing an IV 832 * 833 * The cipher modes CBC, CFB, OFB and CTR all need an "initialization 834 * vector", or short, IV. ECB mode is the only mode that does not require 835 * an IV, but there is almost no legitimate use case for this mode 836 * because of the fact that it does not sufficiently hide plaintext 837 * patterns. Therefore 838 * 839 * <b>You should never use ECB mode unless you are absolutely sure that 840 * you absolutely need it</b> 841 * 842 * Because of this, you will end up with a mode that explicitly requires 843 * an IV in any case. Note that for backwards compatibility reasons, 844 * setting an IV is not explicitly mandated by the Cipher API. If not 845 * set, OpenSSL itself defaults to an all-zeroes IV ("\\0", not the 846 * character). Although the IV can be seen as public information, i.e. 847 * it may be transmitted in public once generated, it should still stay 848 * unpredictable to prevent certain kinds of attacks. Therefore, ideally 849 * 850 * <b>Always create a secure random IV for every encryption of your 851 * Cipher</b> 852 * 853 * A new, random IV should be created for every encryption of data. Think 854 * of the IV as a nonce (number used once) - it's public but random and 855 * unpredictable. A secure random IV can be created as follows 856 * 857 * cipher = ... 858 * cipher.encrypt 859 * key = cipher.random_key 860 * iv = cipher.random_iv # also sets the generated IV on the Cipher 861 * 862 * Although the key is generally a random value, too, it is a bad choice 863 * as an IV. There are elaborate ways how an attacker can take advantage 864 * of such an IV. As a general rule of thumb, exposing the key directly 865 * or indirectly should be avoided at all cost and exceptions only be 866 * made with good reason. 867 * 868 * === Calling Cipher#final 869 * 870 * ECB (which should not be used) and CBC are both block-based modes. 871 * This means that unlike for the other streaming-based modes, they 872 * operate on fixed-size blocks of data, and therefore they require a 873 * "finalization" step to produce or correctly decrypt the last block of 874 * data by appropriately handling some form of padding. Therefore it is 875 * essential to add the output of OpenSSL::Cipher#final to your 876 * encryption/decryption buffer or you will end up with decryption errors 877 * or truncated data. 878 * 879 * Although this is not really necessary for streaming-mode ciphers, it is 880 * still recommended to apply the same pattern of adding the output of 881 * Cipher#final there as well - it also enables you to switch between 882 * modes more easily in the future. 883 * 884 * === Encrypting and decrypting some data 885 * 886 * data = "Very, very confidential data" 887 * 888 * cipher = OpenSSL::Cipher::AES.new(128, :CBC) 889 * cipher.encrypt 890 * key = cipher.random_key 891 * iv = cipher.random_iv 892 * 893 * encrypted = cipher.update(data) + cipher.final 894 * ... 895 * decipher = OpenSSL::Cipher::AES.new(128, :CBC) 896 * decipher.decrypt 897 * decipher.key = key 898 * decipher.iv = iv 899 * 900 * plain = decipher.update(encrypted) + decipher.final 901 * 902 * puts data == plain #=> true 903 * 904 * === Authenticated Encryption and Associated Data (AEAD) 905 * 906 * If the OpenSSL version used supports it, an Authenticated Encryption 907 * mode (such as GCM or CCM) should always be preferred over any 908 * unauthenticated mode. Currently, OpenSSL supports AE only in combination 909 * with Associated Data (AEAD) where additional associated data is included 910 * in the encryption process to compute a tag at the end of the encryption. 911 * This tag will also be used in the decryption process and by verifying 912 * its validity, the authenticity of a given ciphertext is established. 913 * 914 * This is superior to unauthenticated modes in that it allows to detect 915 * if somebody effectively changed the ciphertext after it had been 916 * encrypted. This prevents malicious modifications of the ciphertext that 917 * could otherwise be exploited to modify ciphertexts in ways beneficial to 918 * potential attackers. 919 * 920 * If no associated data is needed for encryption and later decryption, 921 * the OpenSSL library still requires a value to be set - "" may be used in 922 * case none is available. An example using the GCM (Galois Counter Mode): 923 * 924 * cipher = OpenSSL::Cipher::AES.new(128, :GCM) 925 * cipher.encrypt 926 * key = cipher.random_key 927 * iv = cipher.random_iv 928 * cipher.auth_data = "" 929 * 930 * encrypted = cipher.update(data) + cipher.final 931 * tag = cipher.auth_tag 932 * 933 * decipher = OpenSSL::Cipher::AES.new(128, :GCM) 934 * decipher.decrypt 935 * decipher.key = key 936 * decipher.iv = iv 937 * decipher.auth_tag = tag 938 * decipher.auth_data = "" 939 * 940 * plain = decipher.update(encrypted) + decipher.final 941 * 942 * puts data == plain #=> true 943 */ 944 cCipher = rb_define_class_under(mOSSL, "Cipher", rb_cObject); 945 eCipherError = rb_define_class_under(cCipher, "CipherError", eOSSLError); 946 947 rb_define_alloc_func(cCipher, ossl_cipher_alloc); 948 rb_define_copy_func(cCipher, ossl_cipher_copy); 949 rb_define_module_function(cCipher, "ciphers", ossl_s_ciphers, 0); 950 rb_define_method(cCipher, "initialize", ossl_cipher_initialize, 1); 951 rb_define_method(cCipher, "reset", ossl_cipher_reset, 0); 952 rb_define_method(cCipher, "encrypt", ossl_cipher_encrypt, -1); 953 rb_define_method(cCipher, "decrypt", ossl_cipher_decrypt, -1); 954 rb_define_method(cCipher, "pkcs5_keyivgen", ossl_cipher_pkcs5_keyivgen, -1); 955 rb_define_method(cCipher, "update", ossl_cipher_update, -1); 956 rb_define_method(cCipher, "final", ossl_cipher_final, 0); 957 rb_define_method(cCipher, "name", ossl_cipher_name, 0); 958 rb_define_method(cCipher, "key=", ossl_cipher_set_key, 1); 959 rb_define_method(cCipher, "auth_data=", ossl_cipher_set_auth_data, 1); 960 rb_define_method(cCipher, "auth_tag=", ossl_cipher_set_auth_tag, 1); 961 rb_define_method(cCipher, "auth_tag", ossl_cipher_get_auth_tag, -1); 962 rb_define_method(cCipher, "authenticated?", ossl_cipher_is_authenticated, 0); 963 rb_define_method(cCipher, "key_len=", ossl_cipher_set_key_length, 1); 964 rb_define_method(cCipher, "key_len", ossl_cipher_key_length, 0); 965 rb_define_method(cCipher, "iv=", ossl_cipher_set_iv, 1); 966 rb_define_method(cCipher, "iv_len", ossl_cipher_iv_length, 0); 967 rb_define_method(cCipher, "block_size", ossl_cipher_block_size, 0); 968 rb_define_method(cCipher, "padding=", ossl_cipher_set_padding, 1); 969} 970 971