How do I load a private key for SSH authentication using JSch?

To load a private key for SSH authentication using JSch (Java Secure Channel), you can use the addIdentity method available in the JSch class. This method allows you to specify the private key (and optionally, the public key or passphrase) used for key-based authentication.

Here is an example of how to accomplish this:

Example Code

package org.kodejava.jsch;

import com.jcraft.jsch.*;

public class SSHKeyAuthentication {
   public static void main(String[] args) {
      String host = "example.com";
      String user = "username";
      int port = 22; // Default SSH port
      String privateKeyPath = "path/to/your/private_key"; // e.g., ~/.ssh/id_rsa
      String passphrase = "passphrase"; // If your private key is passphrase-protected

      JSch jsch = new JSch();

      try {
         // Add the private key for authentication
         if (passphrase == null || passphrase.trim().isEmpty()) {
            jsch.addIdentity(privateKeyPath); // Without passphrase
         } else {
            jsch.addIdentity(privateKeyPath, passphrase); // With passphrase
         }

         // Establish the SSH session
         Session session = jsch.getSession(user, host, port);

         // Disable host key checking for simplicity (optional, but not recommended in production)
         session.setConfig("StrictHostKeyChecking", "no");

         // Connect to the SSH server
         session.connect();

         System.out.println("Connected to " + host);

         // Do your SSH-related operations here (e.g., opening a channel for SFTP or executing commands)

         // Disconnect once done
         session.disconnect();
         System.out.println("Session disconnected.");
      } catch (JSchException e) {
         e.printStackTrace();
      }
   }
}

Detailed Steps:

  1. Specify the Private Key Path: Replace privateKeyPath with the absolute or relative path to your private key file (e.g., ~/.ssh/id_rsa).

  2. (Optional) Specify Passphrase: If your private key is protected by a passphrase, provide it in the addIdentity method. If there is no passphrase, you can omit it or pass null.

  3. Configure Session Options:

    • For simplicity, the StrictHostKeyChecking option is set to "no", which disables host key verification. However, in production, you should handle the host key verification securely by loading known hosts from a file or verifying the host fingerprint.
  4. Connect and Use the Session: Finally, connect to the SSH server using the connect method and perform desired operations (e.g., file transfer with SFTP or remote command execution).

Notes:

  • Public Key: JSch can also use the public key in conjunction with the private key, but it is optional.
  • Host Keys: It’s better security practice to load and validate the host’s key by explicitly providing a known_hosts file using jsch.setKnownHosts("path/to/known_hosts");.
  • Exception Handling: Always include proper exception handling for scenarios such as incorrect key, server connection failure, or authentication errors.

This code provides a straightforward implementation of loading a private key for SSH authentication with JSch.


Maven Dependencies

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version>
</dependency>

Maven Central

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.