Reputation: 640
I need to use RSA encryption to encode a message. I store the private and public keys in two separate text files, but I can only get as far as encoding a message. I need a way to cast a string into an RSA key, so that I can decode the message.
My code so far:
require 'openssl'
require 'base64'
if File.exist?("./pub_key.txt")
#Keys are strings, I can encrypt but not decrypt a message
pri = File.read("./pri_key.txt")
pub = File.read("./pub_key.txt")
puts pub
string = 'Hello World!';
rsa_public_key = OpenSSL::PKey::RSA.new(pub)
encrypted_string = Base64.encode64(rsa_public_key.public_encrypt(string))
puts encrypted_string
# This throws an error
# Because 'pri' is a string, don't know how to cast it to the right type
#my_string = pri.private_decrypt(Base64.decode64(encrypted_string))
puts "The decoded message"
#puts my_string
end
Upvotes: 0
Views: 4060
Reputation: 640
I fixed the code
Turns out I just needed this line:
rsa_private_key = OpenSSL::PKey::RSA.new(pri)
The full working code
require 'openssl'
require 'base64'
if File.exist?("./pub_key.txt")
#Keys are strings, I can encrypt but not decrypt a message
pri = File.read("./pri_key.txt")
pub = File.read("./pub_key.txt")
puts pub
string = 'Hello World!';
rsa_public_key = OpenSSL::PKey::RSA.new(pub)
rsa_private_key = OpenSSL::PKey::RSA.new(pri)
encrypted_string = Base64.encode64(rsa_public_key.public_encrypt(string))
puts encrypted_string
# This throws an error
# Because 'pri' is a string, don't know how to cast it to the right type
my_string = rsa_private_key .private_decrypt(Base64.decode64(encrypted_string))
puts "The decoded message"
puts my_string
end
Thanks for your time! Rubber duck programming works :)
Upvotes: 2