Sample code for 30+ languages & platforms
Unicode C 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 Unicode C Downloads

Unicode C
#include <C_CkEmailW.h>
#include <C_CkPemW.h>
#include <C_CkCertW.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkEmailW email;
    HCkPemW pem;
    HCkCertW signer;

    success = FALSE;

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

    email = CkEmailW_Create();
    //  The recipient's certificate and private key are in a PEM file.  The 2nd argument of LoadPemFile
    //  is the password of the private key.
    pem = CkPemW_Create();
    success = CkPemW_LoadPemFile(pem,L"recipient.pem",L"RECIPIENT_PASSWORD");
    if (success != TRUE) {
        wprintf(L"%s\n",CkPemW_lastErrorText(pem));
        CkEmailW_Dispose(email);
        CkPemW_Dispose(pem);
        return;
    }

    success = CkEmailW_AddPemSource(email,pem);
    if (success != TRUE) {
        wprintf(L"%s\n",CkEmailW_lastErrorText(email));
        CkEmailW_Dispose(email);
        CkPemW_Dispose(pem);
        return;
    }

    success = CkEmailW_LoadEml(email,L"signed-encrypted.eml");
    if (success != TRUE) {
        wprintf(L"%s\n",CkEmailW_lastErrorText(email));
        CkEmailW_Dispose(email);
        CkPemW_Dispose(pem);
        return;
    }

    if ((CkEmailW_getReceivedEncrypted(email) != TRUE) || (CkEmailW_getDecrypted(email) != TRUE)) {
        wprintf(L"Expected a successfully decrypted S/MIME envelope.\n");
        CkEmailW_Dispose(email);
        CkPemW_Dispose(pem);
        return;
    }

    if ((CkEmailW_getReceivedSigned(email) != TRUE) || (CkEmailW_getSignaturesValid(email) != TRUE)) {
        wprintf(L"Expected a valid signature inside the envelope.\n");
        CkEmailW_Dispose(email);
        CkPemW_Dispose(pem);
        return;
    }

    //  This message has one signer. Examine its certificate after verification.
    signer = CkCertW_Create();
    success = CkEmailW_LastSignerCert(email,0,signer);
    if (success != TRUE) {
        wprintf(L"%s\n",CkEmailW_lastErrorText(email));
        CkEmailW_Dispose(email);
        CkPemW_Dispose(pem);
        CkCertW_Dispose(signer);
        return;
    }

    wprintf(L"Signer certificate: %s\n",CkCertW_subjectDN(signer));
    wprintf(L"Recovered subject: %s\n",CkEmailW_subject(email));
    wprintf(L"Recovered attachments: %d\n",CkEmailW_getNumAttachments(email));


    CkEmailW_Dispose(email);
    CkPemW_Dispose(pem);
    CkCertW_Dispose(signer);

    }