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
?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With