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

C
#include <C_CkPfx.h>
#include <C_CkPrivateKey.h>
#include <C_CkCert.h>
#include <C_CkCertChain.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkPfx pfx;
    HCkPrivateKey privKey;
    HCkCert cert;
    HCkCertChain chain;

    success = FALSE;

    pfx = CkPfx_Create();

    //  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.
    privKey = CkPrivateKey_Create();
    success = CkPrivateKey_LoadPemFile(privKey,"qa_data/private_key.pem");
    if (success == FALSE) {
        printf("%s\n",CkPrivateKey_lastErrorText(privKey));
        CkPfx_Dispose(pfx);
        CkPrivateKey_Dispose(privKey);
        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.
    cert = CkCert_Create();
    success = CkCert_LoadFromFile(cert,"qa_data/cert.pem");
    if (success == FALSE) {
        printf("%s\n",CkCert_lastErrorText(cert));
        CkPfx_Dispose(pfx);
        CkPrivateKey_Dispose(privKey);
        CkCert_Dispose(cert);
        return;
    }

    chain = CkCertChain_Create();
    success = CkCert_BuildCertChain(cert,chain);
    if (success == FALSE) {
        printf("%s\n",CkCert_lastErrorText(cert));
        CkPfx_Dispose(pfx);
        CkPrivateKey_Dispose(privKey);
        CkCert_Dispose(cert);
        CkCertChain_Dispose(chain);
        return;
    }

    //  Add the private key and its certificate chain to the PFX.
    success = CkPfx_AddPrivateKey(pfx,privKey,chain);
    if (success == FALSE) {
        printf("%s\n",CkPfx_lastErrorText(pfx));
        CkPfx_Dispose(pfx);
        CkPrivateKey_Dispose(privKey);
        CkCert_Dispose(cert);
        CkCertChain_Dispose(chain);
        return;
    }

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


    CkPfx_Dispose(pfx);
    CkPrivateKey_Dispose(privKey);
    CkCert_Dispose(cert);
    CkCertChain_Dispose(chain);

    }