Swift
Swift
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 Swift Downloads
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 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
}
// 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)
let cert = CkoCert()!
success = cert.loadPfxFile(path: "qa_data/pfx/example.pfx", password: "pfx_password")
if success != true {
print("\(cert.lastErrorText!)")
return
}
// Get the cert's private key (as PEM) to be used for SSH authentication.
// (The public key is installed on the server.)
var privKeyPem: String? = cert.getPrivateKeyPem()
if cert.lastMethodSuccess == false {
print("\(cert.lastErrorText!)")
return
}
let key = CkoSshKey()!
// Load a private key from a PEM string:
success = key.fromOpenSshPrivateKey(keyStr: privKeyPem)
if success != true {
print("\(key.lastErrorText!)")
return
}
// Authenticate with the SSH server.
success = sftp.authenticatePk(username: "myLogin", privateKey: key)
if success != true {
print("\(sftp.lastErrorText!)")
return
}
print("Public-Key Authentication Successful!")
}