When you are not using one of the constructors of SshClient that automatically performs authentication for you, 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 a number of methods to load private keys, from File, from an InputStream or from a formatted String.
Once you have your SshKeyPair it's then a simple case of passing a PublicKeyAuthenticator instance into your SshClient
ssh.authenticate(new PublicKeyAuthenticator(pair), 30000);
There may be cases where you may not know the passphrase to the key and need to prompt the user for it. If the key is not encrypted this might cause confusion for users, so you can use an alternative method of loading up the SshKeyPair so that you can check if the key is passphrase protected or not. This requires using the more low-level API of SshPrivateKeyFile.
SshPrivateKeyFile pkf = SshPrivateKeyFileFactory.parse(new FileInputStream(new File(".ssh/id_rsa")));
String passphrase = null;
passphrase = reader.readLine();
SshKeyPair pair = pkf.toKeyPair(passphrase);
SSH now supports additional stronger signature methods for RSA keys. If you want to use these, you need to convert a loaded RSA SshKeyPair into one that supports the signature type. Again this is easy with the SshKeyUtils class, it provides methods to do this in a single line of code.
SshKeyPair rsa256sig = SshKeyUtils.makeRSAWithSHA256Signature(pair);
Then you use the SshKeyPair as you would any other, but the signature used when authenticating will be SHA-256. Similarly, you can use SHA-512 signatures by converting the key pair using:
SshKeyPair rsa512sig = SshKeyUtils.makeRSAWithSHA512Signature(pair);