Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 610
bensie Avatar asked Mar 11 '11 08:03

bensie


People also ask

How do I generate a public and private SSH key?

To generate an SSH private/public key pair for your use, you can use the ssh-keygen command-line utility. You can run the ssh-keygen command from the command line to generate an SSH private/public key pair. If you are using Windows, by default you may not have access to the ssh-keygen command.

Which Openssh tool is used to generate public private key pairs?

The ssh-keygen command then does the following: Generates a public key pair. In response to the prompt "Enter passphrase," the user can enter a key passphrase to protect access to the private key. Using a passphrase enhances security, and a passphrase is recommended for sensitive applications.


2 Answers

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}" 
like image 163
benizi Avatar answered Oct 01 '22 00:10

benizi


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.

like image 31
bensie Avatar answered Sep 30 '22 23:09

bensie