Swift Requires Chilkat v11.0.0+
Swift
Sign and encrypt an email with S/MIME
See more Email Object Examples
Use the sender’s signing PFX and the recipient’s public RSA certificate with with-attachments.eml, which has one recipient. Supply your own signing-key password from a credential store. Render to bytes to apply both S/MIME operations without connecting to SMTP.
Chilkat Swift Downloads
func chilkatTest() {
var success: Bool = false
// Assumes Chilkat is unlocked. See Global Unlock Sample.
let email = CkoEmail()!
success = email.loadEml(mimePath: "with-attachments.eml")
if success != true {
print("\(email.lastErrorText!)")
return
}
let signer = CkoCert()!
success = signer.loadPfxFile(path: "signer.pfx", password: "SIGNER_PASSWORD")
if success != true {
print("\(signer.lastErrorText!)")
return
}
let recipient = CkoCert()!
success = recipient.load(fromFile: "recipient.cer")
if success != true {
print("\(recipient.lastErrorText!)")
return
}
success = email.setSigningCert(cert: signer)
if success != true {
print("\(email.lastErrorText!)")
return
}
success = email.setEncryptCert(cert: recipient)
if success != true {
print("\(email.lastErrorText!)")
return
}
email.signingHashAlg = "sha256"
email.pkcs7CryptAlg = "aes"
email.pkcs7KeyLength = 256
email.oaepPadding = true
email.oaepHash = "sha256"
email.oaepMgfHash = "sha256"
email.sendSigned = true
email.sendEncrypted = true
let mail = CkoMailMan()!
let rendered = CkoBinData()!
success = mail.render(toMimeBd: email, renderedMime: rendered)
if success != true {
print("\(mail.lastErrorText!)")
return
}
success = rendered.writeFile(path: "signed-encrypted.eml")
if success != true {
print("Failed: rendered.WriteFile.")
return
}
print("Saved signed-encrypted.eml.")
}