Sample code for 30+ languages & platforms
Swift

SFTP Authentication using an SSH Certificate

See more SFTP Examples

Demonstrates how to SFTP authenticate using an SSH certificate.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    // This example assumes the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    let sbSshCert = CkoStringBuilder()!
    success = sbSshCert.loadFile(path: "qa_data/sshCert/user_ecdsa_key-cert.pub", charset: "utf-8")
    if success == false {
        print("Failed to load user_ecdsa_key-cert.pub")
        return
    }

    let sbPrivKey = CkoStringBuilder()!
    success = sbPrivKey.loadFile(path: "qa_data/sshKeys/user_ecdsa_key", charset: "utf-8")
    if success == false {
        print("Failed to load user_ecdsa_key")
        return
    }

    let key = CkoSshKey()!
    // Provide the password if the user_ecdsa_key is stored in an encrypted format.
    key.password = "secret"
    success = key.fromOpenSshPrivateKey(keyStr: sbPrivKey.getAsString())
    if success == false {
        print("\(key.lastErrorText!)")
        return
    }

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

    let sftp = CkoSFtp()!

    var hostname: String? = "sftp.example.com"
    var port: Int = 22
    success = sftp.connect(hostname: hostname, port: port)
    if success != true {
        print("\(sftp.lastErrorText!)")
        return
    }

    success = sftp.authenticatePk(username: "myLogin", privateKey: key)
    if success != true {
        print("\(sftp.lastErrorText!)")
        return
    }

    print("Public-Key Authentication using an SSH Certificate was Successful!")

}