Sample code for 30+ languages & platforms
Unicode C

Encrypt a File to a PKCS7 (CMS) Message

Shows how to encrypt a file into a PKCS7 encrypted message using the recipient's certificate. Public-key encryption requires no private key. However, the recipient's private key is necessary for decryption.

Chilkat Unicode C Downloads

Unicode C
#include <C_CkCrypt2W.h>
#include <C_CkCertW.h>
#include <C_CkBinDataW.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkCrypt2W crypt;
    HCkCertW cert1;
    HCkBinDataW fileData;

    success = FALSE;

    //  This example requires the Chilkat API to have been previously unlocked.
    //  See Global Unlock Sample for sample code.

    crypt = CkCrypt2W_Create();

    //  Load the recipient's digital certificate. 
    //  We don't need the private key for encryption.
    //  Only the public key is needed (which is included in a certificate).
    cert1 = CkCertW_Create();
    success = CkCertW_LoadFromFile(cert1,L"qa_data/user1/cert_user1.pem");
    //  Assume success for the example, but make sure your application checks for success/failure...
    CkCrypt2W_SetEncryptCert(crypt,cert1);

    //  Indicate that we want PKI encryption (i.e. public-key infrastructure)
    //  to produce a CMS message (Cryptographic Message Syntax/PKCS7),
    //  that is be created with RSAES-OAEP padding, SHA256, and AES-256 for the
    //  bulk encryption.
    CkCrypt2W_putCryptAlgorithm(crypt,L"pki");
    CkCrypt2W_putPkcs7CryptAlg(crypt,L"aes");
    CkCrypt2W_putKeyLength(crypt,256);
    CkCrypt2W_putOaepHash(crypt,L"sha256");
    CkCrypt2W_putOaepPadding(crypt,TRUE);

    //  Load the file to be encrypted...
    fileData = CkBinDataW_Create();
    success = CkBinDataW_LoadFile(fileData,L"qa_data/jpg/penguins.jpg");
    //  Your app should check for success/failure..

    //  Encrypt the data.  The contents of the fileData object are replaced with the PKCS7 encrypted message.
    success = CkCrypt2W_EncryptBd(crypt,fileData);
    if (success != TRUE) {
        wprintf(L"%s\n",CkCrypt2W_lastErrorText(crypt));
        CkCrypt2W_Dispose(crypt);
        CkCertW_Dispose(cert1);
        CkBinDataW_Dispose(fileData);
        return;
    }

    //  Save the PKCS7 encrypted message to a file..
    success = CkBinDataW_WriteFile(fileData,L"qa_output/pkcs7_encrypted.p7");

    wprintf(L"OK.\n");


    CkCrypt2W_Dispose(crypt);
    CkCertW_Dispose(cert1);
    CkBinDataW_Dispose(fileData);

    }