Sample code for 30+ languages & platforms
Unicode C

Create PKCS7 Signed File (.p7m)

See more Encryption Examples

Demonstrates how to sign a file to create a .p7m that contains both the file contents and the signature.

Chilkat Unicode C Downloads

Unicode C
#include <C_CkCrypt2W.h>
#include <C_CkCertStoreW.h>
#include <C_CkJsonObjectW.h>
#include <C_CkCertW.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkCrypt2W crypt;
    HCkCertStoreW certStore;
    HCkJsonObjectW jsonCN;
    HCkCertW cert;
    const wchar_t *inFile;
    const wchar_t *outFile;

    success = FALSE;

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

    crypt = CkCrypt2W_Create();

    certStore = CkCertStoreW_Create();

    // Load a PFX file into a certificate store object.
    success = CkCertStoreW_LoadPfxFile(certStore,L"myPfx.pfx",L"pfxPassword");
    if (success != TRUE) {
        wprintf(L"%s\n",CkCertStoreW_lastErrorText(certStore));
        CkCrypt2W_Dispose(crypt);
        CkCertStoreW_Dispose(certStore);
        return;
    }

    // Get the certificate by subject common name.
    // This should be the cert within the PFX that also
    // has a private key (also stored within the PFX).
    jsonCN = CkJsonObjectW_Create();
    CkJsonObjectW_UpdateString(jsonCN,L"CN",L"myCert");
    cert = CkCertW_Create();
    success = CkCertStoreW_FindCert(certStore,jsonCN,cert);
    if (success == FALSE) {
        wprintf(L"%s\n",CkCertStoreW_lastErrorText(certStore));
        CkCrypt2W_Dispose(crypt);
        CkCertStoreW_Dispose(certStore);
        CkJsonObjectW_Dispose(jsonCN);
        CkCertW_Dispose(cert);
        return;
    }

    // Tell the crypt object to use the certificate for signing:
    success = CkCrypt2W_SetSigningCert(crypt,cert);

    // Sign a file, producing a .p7m as output.
    // The input file is unchanged, the test.p7m contains the 
    // contents of the input file and the signature.
    inFile = L"test.txt";
    outFile = L"testp7m";
    success = CkCrypt2W_CreateP7M(crypt,inFile,outFile);
    if (success != TRUE) {
        wprintf(L"%s\n",CkCrypt2W_lastErrorText(crypt));
        CkCrypt2W_Dispose(crypt);
        CkCertStoreW_Dispose(certStore);
        CkJsonObjectW_Dispose(jsonCN);
        CkCertW_Dispose(cert);
        return;
    }

    wprintf(L"Success!\n");


    CkCrypt2W_Dispose(crypt);
    CkCertStoreW_Dispose(certStore);
    CkJsonObjectW_Dispose(jsonCN);
    CkCertW_Dispose(cert);

    }