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) http://kodehelp.com 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 http://kodehelp.com
 */
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 = "10.20.30.40";
        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 {
			jSch.addIdentity(privateKey);
			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");
            session.setConfig(config);
            session.connect();
            channel = session.openChannel("sftp");
            channel.connect();
            System.out.println("shell channel connected....");
            channelSftp = (ChannelSftp)channel;
            channelSftp.cd(SFTPWORKINGDIR);
            System.out.println("Changed the directory...");
		} catch (JSchException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SftpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(channelSftp!=null){
				channelSftp.disconnect();
				channelSftp.exit();
			}
			if(channel!=null) channel.disconnect();
			
			if(session!=null) session.disconnect();
		}
	}

}