Authenticating the Client using Public Keys

When you are not passing credentials when building the SshClient, then you will need to manually authenticate the client after creating it. We have already dealt with how to perform password authentication in our Creating an SSH Client article, so we will detail how to use the PublicKeyAuthenticator in your programs.

The PublicKeyAuthenticator constructor takes one or more SshKeyPair objects. These are decrypted private keys that are ready to use within authentication. You can decrypt a key to a SshKeyPair using the SshKeyUtils helper class.

SshKeyPair pair = SshKeyUtils.getPrivateKey(new File(".ssh/id_rsa"), "passphrase");

SshKeyUtils provides several methods to load private keys from a File, Path, an InputStream or a formatted String.

Once you have your SshKeyPair, it’s a simple case of passing a PublicKeyAuthenticator instance into your SshClient.

ssh.authenticate(new KeyPairAuthenticator(pair), 30000);

There may be cases where you may not know the passphrase to the key and need to prompt the user for it.

SshKeyPair pair = SshKeyUtils.getPrivateKey(new File(".ssh/id_rsa"),
   (info)-> {
     return new String(System.console().readPassword());
});

You can also load SSH keys from known locations, much like the OpenSSH client does. The IdentityFileAuthenticator does this for you, it will load the following keys if they exist.

~/.ssh/id_ed25519
~/.ssh/id_ed448
~/.ssh/id_rsa
~/.ssh/id_ecdsa

ssh.authenticate(new IdentityFileAuthenticator((info)->{
      System.out.println(info);
      return new String(System.console().readPassword());
}), 3000);

You can also use keys from your ssh-agent. See Authenticating with Keys using the ssh-agent article.