Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening an RSA private key from Ruby

I think I know how to create custom encrypted RSA keys, but how can I read one encrypted like ssh-keygen does?

I know I can do this:

OpenSSL::PKey::RSA.new(File.read('private_key'))

But then OpenSSL asks me for the passphrase... How can I pass it to OpenSSL as a parameter?

And, how can I create one compatible to the ones generated by ssh-keygen?

I do something like this to create private encrypted keys:

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 << c.final

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).

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?

I don't really understand some of this security stuff, but I'm trying to learn. What is it that I'm doing wrong?

like image 280
Ivan Avatar asked Oct 25 '08 01:10

Ivan


People also ask

How do I import my RSA private key?

PrivateKey privateKey = KeyFactory. getInstance("RSA"). generatePrivate( new PKCS8EncodedKeySpec(privateKeyPkcs8));

What do I do with my RSA private key?

The RSA private key is used to generate digital signatures, and the RSA public key is used to verify digital signatures. The RSA public key is also used for key encryption of DES or AES DATA keys and the RSA private key for key recovery.

What is difference between RSA private key and private key?

RSA key is a private key based on RSA algorithm. Private Key is used for authentication and a symmetric key exchange during establishment of an SSL/TLS session. It is a part of the public key infrastructure that is generally used in case of SSL certificates.

Where are private RSA keys stored?

Asymmetric private keys should never be stored verbatim or in plain text on the local computer. If you need to store a private key, use a key container. For more information on key containers, see Understanding machine-level and user-level RSA key containers.


1 Answers

According to the blog post here:

http://stuff-things.net/2008/02/05/encrypting-lots-of-sensitive-data-with-ruby-on-rails/

You can simply do:

OpenSSL::PKey::RSA.new(File.read('private_key'), 'passphrase')

Best of luck.

like image 195
Andy Jeffries Avatar answered Sep 21 '22 07:09

Andy Jeffries