class method
OpenSSL::PKey::RSA.new
() -> ::OpenSSL::PKey::RSA
(::Integer key_size) -> ::OpenSSL::PKey::RSA
(::String encoded_key, ?::String pass_phrase) -> ::OpenSSL::PKey::RSA
RSA.new → rsa
RSA.new(encoded_key [, password ]) → rsa
RSA.new(encoded_key) { password } → rsa
RSA.new(size [, exponent]) → rsa
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 = NULL;
VALUE arg, pass;
int type;
TypedData_Get_Struct(self, EVP_PKEY, &ossl_evp_pkey_type, pkey);
if (pkey)
rb_raise(rb_eTypeError, "pkey already initialized");
/* The RSA.new(size, generator) form is handled by lib/openssl/pkey.rb */
rb_scan_args(argc, argv, "02", &arg, &pass);
if (argc == 0) {
#ifdef OSSL_HAVE_IMMUTABLE_PKEY
rb_raise(rb_eArgError, "OpenSSL::PKey::RSA.new cannot be called " \
"without arguments; pkeys are immutable with OpenSSL 3.0");
#else
rsa = RSA_new();
if (!rsa)
ossl_raise(ePKeyError, "RSA_new");
goto legacy;
#endif
}
pass = ossl_pem_passwd_value(pass);
arg = ossl_to_der_if_possible(arg);
in = ossl_obj2bio(&arg);
/* First try RSAPublicKey format */
rsa = d2i_RSAPublicKey_bio(in, NULL);
if (rsa)
goto legacy;
OSSL_BIO_reset(in);
rsa = PEM_read_bio_RSAPublicKey(in, NULL, NULL, NULL);
if (rsa)
goto legacy;
OSSL_BIO_reset(in);
/* Use the generic routine */
pkey = ossl_pkey_read_generic(in, pass);
BIO_free(in);
if (!pkey)
ossl_raise(ePKeyError, "Neither PUB key nor PRIV key");
type = EVP_PKEY_base_id(pkey);
if (type != EVP_PKEY_RSA) {
EVP_PKEY_free(pkey);
rb_raise(ePKeyError, "incorrect pkey type: %s", OBJ_nid2sn(type));
}
RTYPEDDATA_DATA(self) = pkey;
return self;
legacy:
BIO_free(in);
pkey = EVP_PKEY_new();
if (!pkey || EVP_PKEY_assign_RSA(pkey, rsa) != 1) {
EVP_PKEY_free(pkey);
RSA_free(rsa);
ossl_raise(ePKeyError, "EVP_PKEY_assign_RSA");
}
RTYPEDDATA_DATA(self) = pkey;
return self;
}
Generates or loads an RSA keypair.
If called without arguments, creates a new instance with no key components set. They can be set individually by set_key, set_factors, and set_crt_params. This form is not compatible with OpenSSL 3.0 or later.
If called with a String, tries to parse as DER or PEM encoding of an RSA key. Note that if password is not specified, but the key is encrypted with a password, OpenSSL will prompt for it. See also OpenSSL::PKey.read which can parse keys of any kind.
If called with a number, generates a new key pair. This form works as an alias of RSA.generate.
Examples:
Example
OpenSSL::PKey::RSA.new 2048 OpenSSL::PKey::RSA.new File.read 'rsa.pem' OpenSSL::PKey::RSA.new File.read('rsa.pem'), 'my password'