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

拟墨画扇 提交于 2019-12-30 02:40:06

问题


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 application, 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?


回答1:


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}"



回答2:


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.




回答3:


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/



来源:https://stackoverflow.com/questions/5270386/generate-ssh-keypairs-private-public-without-ssh-keygen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!