Friday, March 14, 2008

SFTP in Java with JSch Using Private Key Authentication

JSch is an excellent library for ssh in Java. One bad thing is that there is no real documentation - or rather, the source itself is the documentation. And the good news is of course that the source code is available along with a nice collection of examples.

I recently had to use SFTP from a Java application and it did take some source-diving to figure out exactly how it works (specifically to get the parameters for JSch.addIdentity right). It turned out to be rather straight-forward:

...

private void execute() throws JSchException, SftpException {
JSch jSch = new JSch();
final byte[] prvkey = readMyPrivateKeyFromFile(); // Private key must be byte array
final byte[] emptyPassPhrase = new byte[0]; // Empty passphrase for now, get real passphrase from MyUserInfo

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

final Vector files = sftp.ls(".");
for (Object obj : files) {
// Do stuff with files
}
sftp.disconnect();
session.disconnect();
}

...

The MyUserInfo class must implement the UserInfo interface. There are a number of good examples of this in the jsch distribution.