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

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

final Vector files =".");
for (Object obj : files) {
// Do stuff with files


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