Search code examples
rubyencryptionrsaprivate-keypublic-key

Need a working Ruby basic RSA Private Public key example


I've been able to create private and public keys with some success, and to encode a message, but on decoding the message I get thrown an error

My code so far is:

require 'openssl'
require 'base64'


key = OpenSSL::PKey::RSA.generate(2048)

pri_key = key
pub_key = key.public_key

string = 'Hello World!';

rsa_public_key = OpenSSL::PKey::RSA.new(pub_key)
encrypted_string = Base64.encode64(rsa_public_key.public_encrypt(string))

puts "Encrypted Message:"
puts encrypted_string

# This creates an error
my_string = pri_key.private_decrypt(encrypted_string)


puts "The decoded message"
puts my_string

This throws this error after printing the encoded message

Example Decrypt.txt:25:in `private_decrypt': data greater than mod len (OpenSSL::PKey::RSAError)
        from Example Decrypt.txt:25:in `<main>'

Solution

  • You base 64 encode the encrypted string, but you don’t decode it before decrypting. Since the base 64 encoded string is longer than the encrypted string, and longer than the modulus, you get the error.

    Try base 64 decoding before encrypting:

    my_string = pri_key.private_decrypt(Base64.decode64(encrypted_string))