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

bensie picture bensie · Mar 11, 2011 · Viewed 9.7k times · Source

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?

Answer

benizi picture benizi · Apr 29, 2012

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