Home > OS >  Can I get the type or fingerprint of a locked SSH private key without unlocking it using JSch?
Can I get the type or fingerprint of a locked SSH private key without unlocking it using JSch?

Time:06-03

UPDATE: @Martin Prikryl's answer is correct however I asked the question because I was getting IllegalStateException with the message encrypted key has not been decrypted yet. when I called getKeyType() so I thought that you can't get info about locked keys. After some more trial and error I found out that the problem was specific to the fork of JSch I use (com.github.mwiede:jsch:0.2.1) that adds support for ED25519 keys and the problem is specific to ED25519 keys. I solved my problem this way:

private static int getKeyType(Path keyFilePath) {
    try {
        Path keyFile = keyFilePath;
        final byte[] key = Files.readAllBytes(keyFile);
        final JSch jSch = new JSch();
        final KeyPair keyPair = KeyPair.load(jSch, key, null);
        return keyPair.getKeyType();
    } catch (final IOException | JSchException e) {
        System.err.println(e.getMessage());
        return 0; // 0 is the key type of ERROR defined in the KeyPair class
    } catch (IllegalStateException e) {
        if (e.getMessage().equals("encrypted key has not been decrypted yet."))
            return 5; // 5 is the key type of ED25519 defined in the KeyPair class
        e.printStackTrace();
        return 0;
    }
}

Can I get the type (RSA, DSA, ECDSA, ED25519...) or the fingerprint of a passphrase protected private ssh key without unlocking it with JSch (like you can in Linux with ssh-keygen -l -f <key_file>)?

I'm writing an Android app and JSch is pretty much the only lib that I managed to get to work with Android so it has to be done with JSch or manually.

CodePudding user response:

Use KeyPair.load to load the key.

And then KeyPair.getKeyType and KeyPair.getFingerPrint to access its properties.

JSch jSch = new JSch();
KeyPair keypair = KeyPair.load(jSch, filename);
System.out.println(keypair.getKeyType());
System.out.println(keypair.getFingerPrint(jSch));
  • Related