Java SSHJ - Add to known_hosts file in verifier

1.3k views Asked by At

I am using SSHJ to execute a remote command, which I can successfully do when the host is in the SSH known_hosts file. However, if the host is not in this file then I would like to the the user the option to add it.

I believe the way to do this is to create a custom HostKeyVerifier (template shown below). However I am struggling to convert the PublicKey into the AAAAB3Nz...cTqGvaDhgtAhw== format to enable me to append the host into the known_hosts file. Can anyone point me in the right direction?

public class CustomVerifier implements HostKeyVerifier {

    public boolean verify(String hostname, int port, PublicKey key) {

        System.out.println(key);    
        System.out.println(KeyType.fromKey(key));
        System.out.println(key.getAlgorithm());
        System.out.println(key.getEncoded());
        System.out.println(key.getFormat());

        return true;
    }

}
1

There are 1 answers

0
Hiery Nomus On

Reading the key from known_hosts is done using the following code (See: OpenSSHKnownHosts.java line 213):

key = new Buffer.PlainBuffer(Base64.decode(sKey)).readPublicKey();

This means that if you have a key, you need to do the reverse:

keyString = Base64.encodeBytes(new Buffer.PlainBuffer().putPublicKey(key).getCompactData());

Or even better, you can extend the OpenSSHKnownHosts class and override the hostKeyUnverifiableAction, similar to how ConsoleKnownHostsVerifier does it.