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

北战南征 提交于 2019-12-18 12:38:17

问题


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...


回答1:


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.



来源:https://stackoverflow.com/questions/3588120/given-a-java-ssh-rsa-publickey-how-can-i-build-an-ssh2-public-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!