Programming Secure FTP in Java

Often server applications need to upload or download files using FTP.  But in this age of increasing security awareness vendors are now asking this be done using SFTP (Secure FTP).

Fortunately this is not difficult using the JSch (Java Secure Channel) library.  The downloadable JSch archive includes numerous examples.  I used the to implement SFTP for my server application.

Starting a connection to an SFTP server using JSch is somewhat simple.

JSch jsch = new JSch();

// start session
session = jsch.getSession(username, host);

// specify our own user info to accept secure connection to FTP server
UserInfo ui = new MyUserInfo(host);

// set password

// connect

// get SFTP channel
Channel channel = session.openChannel("sftp");
schannel = (ChannelSftp) channel;

The trick is getting past confirmation of the authenticity of the host. I do this my creating my own UserInfo implementation, MyUserInfo, which knows about the host I am connecting to. The only method I implement is the promptYesNo method which simply checks if the message is asking about the host I want to connect to.

protected MyUserInfo(final String pKnownHost) {
    this.mKnownHost = pKnownHost;

public boolean promptYesNo(final String pMessage) {
    // message looks like this "The authenticity of host '' can't be established..."
    final int start = pMessage.indexOf("'") + 1;
    final int end = pMessage.indexOf("'", start);
    final String host = pMessage.substring(start, end);

    // is the host a known host?
    return this.mKnownHost.equals(host);

Now uploading is trivial.

schannel.put(src, dest);

For further reading please see Java: What is the best way to SFTP a file from a server.

One thought on “Programming Secure FTP in Java

Leave a Reply

Your email address will not be published. Required fields are marked *