Wednesday, May 13, 2015

SFTP client with private key authentication

SFTP ( FTP over SSH ) is a secure way for file transferring. In JAVA application, you can use the following code to build a SFTP client with private key authentication. Here instead of password pass phase is used.

For this code, JSch JAVA library is used. Following jar files also used for code building.

  • jsch-0.1.51.jar
  • commons-vfs2-2.0.jar
  • commons-logging-1.2.jar

         JSch jSch = new JSch();
        final byte[] privatekey = readMyPrivateKeyFromFile(); // Private key must be byte array
        final byte[] passPhrase = "pass phase".getBytes();

        jSch.addIdentity(
            "myusername",    // String userName
            privatekey,          // byte[] privateKey 
            null,            // byte[] publicKey
            passPhrase  // byte[] passPhrase
        );
        Session session = jSch.getSession("myusername", "hostname", 22);
        UserInfo ui = new UserInfoImpl(); // UserInfoImpl implements UserInfo
        session.setUserInfo(ui);
        session.connect();
        Channel channel = session.openChannel("sftp");
        ChannelSftp sftp = (ChannelSftp) channel;
        sftp.connect();

// Now you can execute any SFTP command for the sftp channel.
        final Vector files = sftp.ls(".");
        for (Object obj : files) {
            System.out.println(obj.toString());
        }
        sftp.disconnect();
        session.disconnect();

No comments:

Post a Comment