Loading Public Key

There are 2 ways to get an instance of RSA Public Key (PKey):

(1) If you are given the actual public key file which looks like:

-----BEGIN PUBLIC KEY-----
MIIB........
............
......
-----END PUBLIC KEY-----

This is straightforward, just load the file and you can get the PKey.

public_key = OpenSSL::PKey::RSA.new(File.read(Rails.root.join('keys', 'my_public_key.pem')))

(2) If you are given the modulus and exponent of the public key. E.g.

modulus = "CECEC82384554............." # A very long string
exponent = "010001"

You can get the PKey by the following steps:

asn1_sequence = OpenSSL::ASN1::Sequence.new([OpenSSL::ASN1::Integer.new(modulus.hex), OpenSSL::ASN1::Integer.new(exponent.hex)]) # It is important that you convert those two values to .hex

public_key = OpenSSL::PKey::RSA.new(asn1_sequence.to_der)

Encryption

Now you have the public key, you can use it to encrypt data:

enc_data = public_key.public_encrypt("my secret data", padding) 
# Note that if padding is not supplied, it defaults to PKCS1_PADDING

Loading Private Key

Your private key should look like this:

-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAz........
........
-----END RSA PRIVATE KEY-----

Load the private key the same way you load the public key file:

private_key = OpenSSL::PKey::RSA.new(File.read(Rails.root.join('keys', 'my_private_key.pem')))

Decryption

Finally, you can decrypt the data by the following code:

private_key.private_decrypt(enc_data)