ssh使用的密钥格式在RFC#4253中定义。RSA公钥的格式如下:
string "ssh-rsa" mpint e mpint n
所有数据类型编码均在RFC#4251的#5部分中定义。字符串和mpint(多精度整数)类型的编码方式如下:
4-bytes word: data length (unsigned big-endian 32 bits integer) n bytes : binary representation of the data
例如,字符串“ ssh-rsa”的编码为:
byte[] data = new byte[] {0, 0, 0, 7, 's', 's', 'h', '-', 'r', 's', 'a'};编码公众:
public byte[] enprePublicKey(RSAPublicKey key) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] sshrsa = new byte[] {0, 0, 0, 7, 's', 's', 'h', '-', 'r', 's', 'a'}; out.write(sshrsa); BigInteger e = key.getPublicExponent(); byte[] data = e.toByteArray(); enpreUInt32(data.length, out); out.write(data); BigInteger m = key.getModulus(); data = m.toByteArray(); enpreUInt32(data.length, out); out.write(data); return out.toByteArray(); } public void enpreUInt32(int value, OutputStream out) throws IOException { byte[] tmp = new byte[4]; tmp[0] = (byte)((value >>> 24) & 0xff); tmp[1] = (byte)((value >>> 16) & 0xff); tmp[2] = (byte)((value >>> 8) & 0xff); tmp[3] = (byte)(value & 0xff); out.write(tmp); }要获得密钥的字符串表示形式,只需在base64中编码返回的字节数组即可。
对于私钥编码,有两种情况:
- 私钥不受密码保护。在那种情况下,私钥根据PKCS#8标准进行编码,然后使用base64进行编码。它可以通过打电话来获得私钥的PKCS8编码
getEnpred
上RSAPrivateKey
。 - 私钥受密码保护。在这种情况下,密钥编码是OpenSSH专用格式。我不知道是否有任何格式的文档(当然,OpenSSH源代码除外)



