title: Ruby, how to convert a string to an RSA public key
body: <p>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.</p>
  
  <p>My code so far:</p>
  
  <pre><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)
    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
  </code></pre>