Sample code for 30+ languages & platforms
Java Requires Chilkat v11.0.0+

SFTP Authentication using an SSH Certificate

See more SFTP Examples

Demonstrates how to SFTP authenticate using an SSH certificate.

Chilkat Java Downloads

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

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.

        StringBuilder sbSshCert = new StringBuilder();
        try {
            sbSshCert.loadFile("qa_data/sshCert/user_ecdsa_key-cert.pub", "utf-8");
        } catch (ChilkatException e) {
            System.out.println("Failed to load user_ecdsa_key-cert.pub");
            return;
        }

        StringBuilder sbPrivKey = new StringBuilder();
        try {
            sbPrivKey.loadFile("qa_data/sshKeys/user_ecdsa_key", "utf-8");
        } catch (ChilkatException e) {
            System.out.println("Failed to load user_ecdsa_key");
            return;
        }

        SshKey key = new SshKey();
        // Provide the password if the user_ecdsa_key is stored in an encrypted format.
        key.setPassword("secret");
        try {
            key.fromOpenSshPrivateKey(sbPrivKey.getAsString());
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Indicate that the SSH certificate is to be used for authentication.
        // The UseSshCertificate method was added in Chilkat v11.0.0
        key.useSshCertificate(sbSshCert.getAsString());

        SFtp sftp = new SFtp();

        String hostname = "sftp.example.com";
        int port = 22;
        try {
            sftp.connect(hostname, port);

            sftp.authenticatePk("myLogin", key);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        System.out.println("Public-Key Authentication using an SSH Certificate was Successful!");
    }
}