title: Opening an RSA private key from Ruby
body: <p>I <em>think</em> I know how to create custom encrypted RSA keys, but how can I read one encrypted like ssh-keygen does?</p>
  
  <p>I know I can do this:</p>
  
  <pre><code>OpenSSL::PKey::RSA.new(File.read('private_key'))
  </code></pre>
  
  <p>But then OpenSSL asks me for the passphrase... How can I pass it to OpenSSL as a parameter?</p>
  
  <p>And, how can I create one compatible to the ones generated by ssh-keygen?</p>
  
  <p>I do something like this to create private encrypted keys:</p>
  
  <pre><code>pass = '123456'
  key = OpenSSL::PKey::RSA.new(1024)
  key = "0000000000000000#{key.to_der}"
  c = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
  c.encrypt
  c.key = Digest::SHA1.hexdigest(pass).unpack('a2' * 32).map {|x| x.hex}.pack('c' * 32)
  c.iv = iv
  encrypted_key = c.update(key)
  encrypted_key &lt;&lt; c.final
  </code></pre>
  
  <p>Also, keys generated by OpenSSL::PKey::RSA.new(1024) (without encryption), don't work when I try password-less logins (i.e., I copy the public key to the server and use the private one to login).</p>
  
  <p>Also, when I open an ssh-keygen file via OpenSSL and then check its contents, it appears to have additional characters at the beginning and end of the key. Is this normal?</p>
  
  <p>I don't really understand some of this security stuff, but I'm trying to learn. What is it that I'm doing wrong?</p>