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;
}
}
Reading the key from
known_hosts
is done using the following code (See: OpenSSHKnownHosts.java line 213):This means that if you have a key, you need to do the reverse:
Or even better, you can extend the
OpenSSHKnownHosts
class and override thehostKeyUnverifiableAction
, similar to howConsoleKnownHostsVerifier
does it.