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.
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;
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With