Authenticating with public/private keys

Lee Painter

This article assumes you have already created a SshClient and are ready to authenticate it. For more information on creating a SshClient see the article

Creating a connection

In order to authenticate with a key, you need to create an instance of PublicKeyAuthentication and pass it to the SshClient's authenticate method.

For example, you can load a key from a standard private key file and passphrase using the code:

PublicKeyAuthentication pk = new PublicKeyAuthentication(new File(".ssh/id_rsa"), "mypassphrase");>

If the file in question does not have a passphrase simply pass null:

PublicKeyAuthentication pk = new PublicKeyAuthentication(new File(".ssh/id_rsa"), null);

If your private key is stored somewhere other than a file, for example in a database, you can load the private key using an InputStream

InputStream in = ...
PublicKeyAuthentication pk = new PublicKeyAuthentication(in, "mypassphrase");

Or if you have a String containing the private key file text

String key = ...
PublicKeyAuthentication pk = new PublicKeyAuthentication(key, "mypassphrase");

To authenticate 

int result = ssh.authenticate(pk);

For information on how to process the result see Processing the authentication result.