Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using public key from authorized_keys with Java security

How can I use an entry from the systems authorized_keys file for a java.security.PublicKey implementation? I specifically want to compare a public key from the authorized_keys file with a public key available in the Apache SSHD PublickeyAuthenticator interface.

like image 941
DerMike Avatar asked Aug 20 '10 13:08

DerMike


1 Answers

The same solution but delegates the decodeInt() to the DataInputStream. I remove from the original code the BouncyCastleProvider for the KeyFactory as soon as it already knows the RSA algorithm.

Original source : https://github.com/ragnar-johannsson/CloudStack/blob/master/utils/src/com/cloud/utils/crypt/RSAHelper.java

private static RSAPublicKey readKey(String key) throws Exception {
    // key = "ssh-rsa <myBase64key> <email>"
    byte[] encKey = Base64.decodeBase64(key.split(" ")[1]);
    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(encKey));

    byte[] header = readElement(dis);
    String pubKeyFormat = new String(header);
    if (!pubKeyFormat.equals("ssh-rsa"))
    throw new RuntimeException("Unsupported format");

    byte[] publicExponent = readElement(dis);
    byte[] modulus = readElement(dis);

    KeySpec spec = new RSAPublicKeySpec(new BigInteger(modulus), new BigInteger(publicExponent));
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(spec);

    return pubKey;
}

private static byte[] readElement(DataInput dis) throws IOException {
    int len = dis.readInt();
    byte[] buf = new byte[len];
    dis.readFully(buf);
    return buf;
}
like image 161
Guillaume Lecroc Avatar answered Oct 12 '22 12:10

Guillaume Lecroc