Swift
Swift
SSH Tunnel Authenticate with Secure Strings
See more SSH Examples
Demonstrates SSH tunnel password authentication using SecureString objects, with the credentials read from an encrypted JSON config file and decrypted directly into secure strings rather than being hard-coded in source.
Background: The
SshTunnel class runs the tunnel on a background thread, so it authenticates once and then serves connections until closed — which makes protecting the stored credential especially worthwhile. Decrypting straight into a SecureString avoids ever holding the password in an ordinary string, and the value stays encrypted in memory under a randomly generated session key. In production the decryption key itself would come from a key vault or OS keystore rather than a literal.Chilkat Swift Downloads
func chilkatTest() {
var success: Bool = false
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// Demonstrates SSH tunnel password authentication using SecureString objects, with the
// credentials read from an encrypted config file rather than hard-coded in source.
// Imagine the login and password were previously encrypted and saved in a JSON config file:
// {
// "ssh_login": "2+qylFfC56Ck7OQQt/U2/w==",
// "ssh_password": "5neIq9Jmn0E3p71N6Yc8TA=="
// }
let json = CkoJsonObject()!
success = json.loadFile(path: "qa_data/passwords/ssh.json")
if success == false {
print("\(json.lastErrorText!)")
return
}
// These are the encryption settings used when the credentials were encrypted. In a real
// application the key would come from a secure source, not a literal.
let crypt = CkoCrypt2()!
crypt.cryptAlgorithm = "aes"
crypt.cipherMode = "cbc"
crypt.keyLength = 128
crypt.setEncodedKey(keyStr: "000102030405060708090A0B0C0D0E0F", encoding: "hex")
crypt.setEncodedIV(ivStr: "000102030405060708090A0B0C0D0E0F", encoding: "hex")
crypt.encodingMode = "base64"
// Decrypt directly into SecureString objects. The values stay encrypted in memory, now under
// a randomly generated session key.
let ssLogin = CkoSecureString()!
let ssPassword = CkoSecureString()!
crypt.decryptSecureENC(cipherText: json.string(of: "ssh_login"), secureStr: ssLogin)
crypt.decryptSecureENC(cipherText: json.string(of: "ssh_password"), secureStr: ssPassword)
let tunnel = CkoSshTunnel()!
var port: Int = 22
success = tunnel.connect(hostname: "ssh.example.com", port: port)
if success == false {
print("\(tunnel.lastErrorText!)")
return
}
// Authenticate using the secure strings.
success = tunnel.authenticateSecPw(login: ssLogin, password: ssPassword)
if success == false {
print("\(tunnel.lastErrorText!)")
return
}
print("SSH tunnel authentication successful.")
// ... use the tunnel ...
var waitForThreadExit: Bool = true
success = tunnel.closeTunnel(waitForThreads: waitForThreadExit)
if success == false {
print("\(tunnel.lastErrorText!)")
return
}
}