Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a Java ssh-rsa PublicKey, how can I build an SSH2 public key?

I'm doing publicKey.getEncoded(), then appending "ssh-rsa" to the front, then base64 encoding it. Then I add the SSH2 header/footer. But it won't decode...

like image 405
pizzathehut Avatar asked Aug 27 '10 21:08

pizzathehut


1 Answers

Java public keys are encoded as a standard X.509 SubjectPublicKeyInfo structure.

SSH2 uses its own simple format. Base-64 encode the result of the encode method shown below, and affix the necessary SSH2 header and footer.

public static byte[] encode(RSAPublicKey key)
  throws IOException
{
  ByteArrayOutputStream buf = new ByteArrayOutputStream();
  byte[] name = "ssh-rsa".getBytes("US-ASCII");
  write(name, buf);
  write(key.getPublicExponent().toByteArray(), buf);
  write(key.getModulus().toByteArray(), buf);
  return buf.toByteArray();
}

private static void write(byte[] str, OutputStream os)
  throws IOException
{
  for (int shift = 24; shift >= 0; shift -= 8)
    os.write((str.length >>> shift) & 0xFF);
  os.write(str);
}

See this answer for converting the other direction, from OpenSSH to Java.

like image 53
erickson Avatar answered Oct 31 '22 12:10

erickson