Search code examples
javaopenssh

Converting openssh public key to ssh2 (RFC 4716) format


The main question is just that. Parse the openssh public key to rfc 4716 format compliant. The only catch though, is that it has to be in java.

Using ssh-keygen, it is just single line command :

ssh-keygen -e -f openssh_key.pub

Unfortunately, I couldn't find any other sources to do so in Java. Even any algorithm or steps necessary for the conversion are not mentioned. All of them revolve around usage of ssh-keygen itself. Ofcourse, I can use java.exec to call the command, but that is the worst case scenario.


Example openssh key (Have kept it in code format so as to retain the spaces/new-line as was produced) :

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDwxgE7D3HYLYddNHLMFK8OfpRwwUSgxiB8fbecvkCUEktSpWikvsWTyCnl5p3uSmsGg/F1lwVPXuuVlQ4VZlYqMuEBEMRF9ADdXWWNxjO/Hd7688ow7ocncxl0xKXsH5Fc9GHvE8yfUh94F8Qm9x8M8Uux+XsNEvPG8KI/QUJWndIsHv+m//3nbEEqUTAlzsyY0mjHW/dPORhXcB5WeGH+cBRAhcp5JGKAq26TOsuNY8H+nrlxX6z03xbUN28HHdXv6uKZfpnVpl6tM0khxbh7F+tLYWeUIZ+nYaDBPINv8Mkd6Duqe/GOLtgVUIR76Adijok4w5oaKlTq27xzMurl kaushik@kaushik-HP

Parsed using ssh-keygen :

---- BEGIN SSH2 PUBLIC KEY ----
Comment: "2048-bit RSA, converted by kaushik@kaushik-HP from OpenSSH"
AAAAB3NzaC1yc2EAAAADAQABAAABAQDwxgE7D3HYLYddNHLMFK8OfpRwwUSgxiB8fbecvk
CUEktSpWikvsWTyCnl5p3uSmsGg/F1lwVPXuuVlQ4VZlYqMuEBEMRF9ADdXWWNxjO/Hd76
88ow7ocncxl0xKXsH5Fc9GHvE8yfUh94F8Qm9x8M8Uux+XsNEvPG8KI/QUJWndIsHv+m//
3nbEEqUTAlzsyY0mjHW/dPORhXcB5WeGH+cBRAhcp5JGKAq26TOsuNY8H+nrlxX6z03xbU
N28HHdXv6uKZfpnVpl6tM0khxbh7F+tLYWeUIZ+nYaDBPINv8Mkd6Duqe/GOLtgVUIR76A
dijok4w5oaKlTq27xzMurl
---- END SSH2 PUBLIC KEY ----

UPDATE : I have created an implementation of the conversion on gist, for anyone with similar needs.


Solution

  • The Base64 data in the two formats is identical -- you don't need to do anything fancy. All you need to do to convert between these formats is add/remove line breaks (at 70 characters) and change the header/trailer.

    Note that both formats have a comment -- kaushik@kaushik-HP in the OpenSSH key, and the line starting with Comment: in the PEM key. Both are completely optional, and don't need to be converted.