Equivalent of openssl_public_encrypt PHP function in Ruby

271 views Asked by At

I would like to obtain an equivalent of the code below in ruby:

$key = '-----BEGIN PUBLIC KEY-----
some public key
-----END PUBLIC KEY-----';

$cc_number = '4242424242424242';
openssl_public_encrypt($cc_number, $cc_number_encrypted, $key);
echo base64_encode($cc_number_encrypted);

I tried:

pkey = '-----BEGIN PUBLIC KEY-----
some public key
-----END PUBLIC KEY-----'

cc = '4242424242424242'
key = OpenSSL::PKey::RSA.new(pkey)
puts Base64.encode64(key.public_encrypt(cc)) 

but it doesn't work. How to write this PHP code in Ruby?

1

There are 1 answers

0
d3m0n On

I found the solution inspired by this question: Strange \n in base64 encoded string in Ruby.

I had to change:

puts Base64.encode64(key.public_encrypt(cc)) 

to

puts Base64.strict_encode64(key.public_encrypt(cc)) 

As the documentation says:

This method complies with RFC 4648. No line feeds are added.