Swift
Swift
Generate an RSA Key and Save to Encrypted PEM
See more RSA Examples
Demonstrates how to generate an RSA key and save to an encrypted PEM file.Chilkat Swift Downloads
func chilkatTest() {
var success: Bool = false
let rsa = CkoRsa()!
// Generate a 2048-bit key.
let privKey = CkoPrivateKey()!
success = rsa.genKey(numBits: 2048, privKey: privKey)
if success == false {
print("\(rsa.lastErrorText!)")
return
}
var password: String? = "secret"
// Saving to a relative path (from the current working directory of the process).
var path: String? = "rsaKeys/myTestRsaPrivate.pem"
// Encrypt the PEM using 256-bit AES encryption.
privKey.pkcs8EncryptAlg = "aes256"
success = privKey.savePkcs8EncryptedPemFile(password: password, path: path)
if success == false {
print("\(privKey.lastErrorText!)")
return
}
//
// We can also save the public key.
// There is no need to encrypt public keys.
let pubKey = CkoPublicKey()!
privKey.toPublicKey(pubKey: pubKey)
path = "rsaKeys/myTestRsaPublic.pem"
// Choose PKCS1 or PKCS8
// We'll choose PKCS8.
var preferPkcs1: Bool = false
success = pubKey.savePemFile(preferPkcs1: preferPkcs1, path: path)
if success == false {
print("\(pubKey.lastErrorText!)")
return
}
//
print("Success.")
}