Sample code for 30+ languages & platforms
Java

SFTP Authentication using X.509 Certificates

See more SFTP Examples

Demonstrates how to authenticate with an SSH/SFTP server using an certificate's private key.

Note: See X.509v3 Certificates for SSH Authentication for more information.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.Cert;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.SFtp;
import com.chilkatsoft.chilkat2.SshKey;

public class ChilkatExample {

    public static void main(String[] args) {
        // This example assumes the Chilkat API to have been previously unlocked.
        // See Global Unlock Sample for sample code.

        SFtp sftp = new SFtp();

        String hostname = "sftp.example.com";
        int port = 22;
        try {
            sftp.connect(hostname, port);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Load the cert + private key from a .pfx.
        // Note: Chilkat provides methods for loading certs and private keys from many sources, including smart cards and USB tokens (HSM's)
        Cert cert = new Cert();
        String privKeyPem;
        try {
            cert.loadPfxFile("qa_data/pfx/example.pfx", "pfx_password");

            // Get the cert's private key (as PEM) to be used for SSH authentication.
            // (The public key is installed on the server.)
            privKeyPem = cert.getPrivateKeyPem();
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        SshKey key = new SshKey();

        // Load a private key from a PEM string:
        try {
            key.fromOpenSshPrivateKey(privKeyPem);

            // Authenticate with the SSH server.
            sftp.authenticatePk("myLogin", key);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        System.out.println("Public-Key Authentication Successful!");
    }
}