How to make SFTP or SSH connection using public key authentication in java?

DeeKay May 11, 2015 at 7:32 pm · How To

Using SSH public key authentication to make the connection to remote system is more secure and robust method than login with account password. SSH public key authentication is an authentication method that relies on asymmetric cryptographic algorithms that generate a pair of  separate keys, one private and the other public. Private Key is the secret key which is stored on the computer you use to connect to the remote system. Public key as the name suggest you can share with anyone without compromising the Private Key  and it stored on the remote system which you will be accessing.

Pre-requisite for making SFTP or SSH connection using public key authentication is –

Please use below java program to make SFTP/SSH connection. This java program uses JSch java API to make SFTP/SSH connection.

 * Created on Apr 7, 2015 Copyright(c) All Rights Reserved.
package com.kodehelp.sftp;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

 * This java program shows you how to make SFTP/SSH connection with public key using JSch java API
 * @author
public class SFTPinJava {

	 * @param args
	public static void main(String[] args) {
		/*Below we have declared and defined the SFTP HOST, PORT, USER 
		           and Local private key from where you will make connection */
		String SFTPHOST = "";
        int    SFTPPORT = 22;
        String SFTPUSER = "kodehelp";
        // this file can be id_rsa or id_dsa based on which algorithm is used to create the key
        String privateKey = "/home/kodehelp/.ssh/id_rsa"; 
        String SFTPWORKINGDIR = "/home/kodehelp/";
        JSch jSch = new JSch();
        Session     session     = null;
        Channel     channel     = null;
        ChannelSftp channelSftp = null;
        try {
			System.out.println("Private Key Added.");
			session = jSch.getSession(SFTPUSER,SFTPHOST,SFTPPORT);
            System.out.println("session created.");
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            channel = session.openChannel("sftp");
            System.out.println("shell channel connected....");
            channelSftp = (ChannelSftp)channel;
            System.out.println("Changed the directory...");
		} catch (JSchException e) {
			// TODO Auto-generated catch block
		} catch (SftpException e) {
			// TODO Auto-generated catch block
			if(channel!=null) channel.disconnect();
			if(session!=null) session.disconnect();