Method: OpenSSL::Cipher#key=

Defined in:
ossl_cipher.c

#key=(string) ⇒ String

Sets the cipher key. To generate a key, you should either use a secure random byte string or, if the key is to be derived from a password, you should rely on PBKDF2 functionality provided by OpenSSL::PKCS5. To generate a secure random-based key, Cipher#random_key may be used.

Only call this method after calling Cipher#encrypt or Cipher#decrypt.

Returns:

  • (String)


470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
# File 'ossl_cipher.c', line 470

static VALUE
ossl_cipher_set_key(VALUE self, VALUE key)
{
    EVP_CIPHER_CTX *ctx;
    int key_len;

    StringValue(key);
    GetCipher(self, ctx);

    key_len = EVP_CIPHER_CTX_key_length(ctx);
    if (RSTRING_LEN(key) != key_len)
	ossl_raise(rb_eArgError, "key must be %d bytes", key_len);

    if (EVP_CipherInit_ex(ctx, NULL, NULL, (unsigned char *)RSTRING_PTR(key), NULL, -1) != 1)
	ossl_raise(eCipherError, NULL);

    rb_ivar_set(self, id_key_set, Qtrue);

    return key;
}