Documentation
Open Source Release Policy
Export Compliance
Using BouncyCastle
Installing the API
Enabling Logging
Per-Connection Logging
Third Party Dependencies
Generating SSH Keys
Using BouncyCastle
Using SSH Public Keys in Java
Supporting ED25519/Curve25519
Supporting Compression
Integrating Licensing into Maven Builds
Creating an SSH Client
Public Key Authentication
Keyboard Interactive Authentication
Public Key Authentication with sshagent
Executing Single Commands
Executing Commands within a Shell
Transferring Files
Connecting through Proxies
Display the Authentication Banner
Using the SFTP Client
Port Forwarding
Working Examples
Configuring Listening Interfaces
Configuring Host Keys
Password Authentication
Public Key Authentication
Challenge-Response Authentication
Configuring Port Forwarding
Configuring SFTP
Supporting SCP
Implementing your own File System
Creating an Interactive Terminal
Proxy Protocol Support
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");
Code language: JavaScript (javascript)
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);
Code language: JavaScript (javascript)
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());
});
Code language: JavaScript (javascript)
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);
Code language: JavaScript (javascript)
You can also use keys from your ssh-agent. See Authenticating with Keys using the ssh-agent article.