Sample code for 30+ languages & platforms
Unicode C++

Add a Private Key and Certificate Chain to a PFX

See more PFX/P12 Examples

Demonstrates Pfx.AddPrivateKey, which adds a private key together with its certificate chain to the PFX object.

The file path is relative to the application's current working directory. An absolute path may also be used. Supply the path appropriate to your own environment.

Background. The chain must contain at least one certificate; the certificate at index 0 is treated as the leaf. The chain is built here with Cert.BuildCertChain.

Chilkat Unicode C++ Downloads

Unicode C++
#include <CkPfxW.h>
#include <CkPrivateKeyW.h>
#include <CkCertW.h>
#include <CkCertChainW.h>

void ChilkatSample(void)
    {
    bool success = false;

    CkPfxW pfx;

    //  The file path is relative to the application's current working directory.  An absolute path
    //  may also be used.  Supply the path appropriate to your own environment.
    //  Load the private key.
    CkPrivateKeyW privKey;
    success = privKey.LoadPemFile(L"qa_data/private_key.pem");
    if (success == false) {
        wprintf(L"%s\n",privKey.lastErrorText());
        return;
    }

    //  Load the certificate and build its chain of authority.  The chain must contain at least one
    //  certificate; the certificate at index 0 is treated as the leaf.
    CkCertW cert;
    success = cert.LoadFromFile(L"qa_data/cert.pem");
    if (success == false) {
        wprintf(L"%s\n",cert.lastErrorText());
        return;
    }

    CkCertChainW chain;
    success = cert.BuildCertChain(chain);
    if (success == false) {
        wprintf(L"%s\n",cert.lastErrorText());
        return;
    }

    //  Add the private key and its certificate chain to the PFX.
    success = pfx.AddPrivateKey(privKey,chain);
    if (success == false) {
        wprintf(L"%s\n",pfx.lastErrorText());
        return;
    }

    wprintf(L"Private key and certificate chain added to the PFX.\n");
    }