End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
class method
OpenSSL::PKey::RSA.new
RSA.new(key_size) => RSA instance
RSA.new(encoded_key) => RSA instance
RSA.new(encoded_key, pass_phrase) => RSA instance
ext/openssl/ossl_pkey_rsa.c
View on GitHub ↗
static VALUE
ossl_rsa_initialize(int argc, VALUE *argv, VALUE self)
{
EVP_PKEY *pkey;
RSA *rsa;
BIO *in;
VALUE arg, pass;
GetPKey(self, pkey);
if(rb_scan_args(argc, argv, "02", &arg, &pass) == 0) {
rsa = RSA_new();
}
else if (RB_INTEGER_TYPE_P(arg)) {
rsa = rsa_generate(NUM2INT(arg), NIL_P(pass) ? RSA_F4 : NUM2ULONG(pass));
if (!rsa) ossl_raise(eRSAError, NULL);
}
else {
pass = ossl_pem_passwd_value(pass);
arg = ossl_to_der_if_possible(arg);
in = ossl_obj2bio(&arg);
rsa = PEM_read_bio_RSAPrivateKey(in, NULL, ossl_pem_passwd_cb, (void *)pass);
if (!rsa) {
OSSL_BIO_reset(in);
rsa = PEM_read_bio_RSA_PUBKEY(in, NULL, NULL, NULL);
}
if (!rsa) {
OSSL_BIO_reset(in);
rsa = d2i_RSAPrivateKey_bio(in, NULL);
}
if (!rsa) {
OSSL_BIO_reset(in);
rsa = d2i_RSA_PUBKEY_bio(in, NULL);
}
if (!rsa) {
OSSL_BIO_reset(in);
rsa = PEM_read_bio_RSAPublicKey(in, NULL, NULL, NULL);
}
if (!rsa) {
OSSL_BIO_reset(in);
rsa = d2i_RSAPublicKey_bio(in, NULL);
}
BIO_free(in);
if (!rsa) {
ossl_raise(eRSAError, "Neither PUB key nor PRIV key");
}
}
if (!EVP_PKEY_assign_RSA(pkey, rsa)) {
RSA_free(rsa);
ossl_raise(eRSAError, NULL);
}
return self;
}
Generates or loads an RSA keypair. If an integer key_size is given it represents the desired key size. Keys less than 1024 bits should be considered insecure.
A key can instead be loaded from an encoded_key which must be PEM or DER encoded. A pass_phrase can be used to decrypt the key. If none is given OpenSSL will prompt for the pass phrase.
Examples
Example
OpenSSL::PKey::RSA.new 2048 OpenSSL::PKey::RSA.new File.read 'rsa.pem' OpenSSL::PKey::RSA.new File.read('rsa.pem'), 'my pass phrase'