Sample code for 30+ languages & platforms
Swift Requires Chilkat v11.8.0+

Decrypt an S/MIME email and verify its signature

See more Email Object Examples

Register the recipient’s certificate and private key (from a PEM file) before opening signed-encrypted.eml. This workflow expects both encryption and a signature, so it checks both layers before reading the message. Cryptographic signature validity is one input to a signer-trust decision.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.

    let email = CkoEmail()!
    //  The recipient's certificate and private key are in a PEM file.  The 2nd argument of LoadPemFile
    //  is the password of the private key.
    let pem = CkoPem()!
    success = pem.loadFile(path: "recipient.pem", password: "RECIPIENT_PASSWORD")
    if success != true {
        print("\(pem.lastErrorText!)")
        return
    }

    success = email.addPemSource(pem: pem)
    if success != true {
        print("\(email.lastErrorText!)")
        return
    }

    success = email.loadEml(mimePath: "signed-encrypted.eml")
    if success != true {
        print("\(email.lastErrorText!)")
        return
    }

    if (email.receivedEncrypted != true) || (email.decrypted != true) {
        print("Expected a successfully decrypted S/MIME envelope.")
        return
    }

    if (email.receivedSigned != true) || (email.signaturesValid != true) {
        print("Expected a valid signature inside the envelope.")
        return
    }

    //  This message has one signer. Examine its certificate after verification.
    let signer = CkoCert()!
    success = email.lastSignerCert(index: 0, cert: signer)
    if success != true {
        print("\(email.lastErrorText!)")
        return
    }

    print("Signer certificate: \(signer.subjectDN!)")
    print("Recovered subject: \(email.subject!)")
    print("Recovered attachments: \(email.numAttachments.intValue)")

}