开发者

Generate SSH Keypairs (private/public) without ssh-keygen

I'm working on a Ruby/Rack application that needs to generate SSH keypairs. As much as I'd like to call ssh-keygen from the ap开发者_Python百科plication, I can't because it's designed to run on Heroku and they don't support calling that command.

I've been able to get private/public RSA keys using OpenSSL in the Ruby standard library doing the following:

key = OpenSSL::PKey::RSA.generate(2048)
# => -----BEGIN RSA PRIVATE KEY----- ....
key.public_key
# => -----BEGIN RSA PUBLIC KEY----- ....

Unfortunately an RSA public key and an SSH public key is not the same thing, even though they can be generated from the same RSA key. An SSH public key looks something like the following:

ssh-rsa AAAAB3NzaC1yc2EAAAABIwA.....

Is it possible to generate SSH keys or convert RSA keys to SSH in Ruby without using ssh-keygen?


It may not have been the case when you had the problem, but the net-ssh library patches OpenSSL::PKey::RSA and ::DSA with two methods:

#ssh_type - returns "ssh-rsa" or "ssh-dss" as appropriate

and #to_blob - returns the public key in OpenSSH binary-blob format. If you base64-encode it, it's the format you're looking for.

require 'net/ssh'

key = OpenSSL::PKey::RSA.new 2048

type = key.ssh_type
data = [ key.to_blob ].pack('m0')

openssh_format = "#{type} #{data}"


Turns out this was much more complicated than I anticipated. I ended up writing the SSHKey gem to pull it off (source code on GitHub). SSH Public keys are encoded totally differently from the RSA public key provided. Data type encoding for SSH keys are defined in section #5 of RFC #4251.


key.public_key.to_pem

The full process including key encryption is documented here: http://stuff-things.net/2009/12/11/generating-rsa-key-pairs-in-ruby/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜