Sample code for 30+ languages & platforms
Unicode C

Iterate Keys and Certs in PEM

See more PEM Examples

Demonstrates how to access each of the private keys and certs contained within a PEM.

Chilkat Unicode C Downloads

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

void ChilkatSample(void)
    {
    BOOL success;
    HCkPemW pem;
    const wchar_t *password;
    const wchar_t *pemContent;
    int numPrivateKeys;
    int i;
    HCkPrivateKeyW privKey;
    HCkCertW cert;
    int numCerts;

    success = FALSE;

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

    pem = CkPemW_Create();

    // Load the PEM from a file.
    // If the PEM is encrypted, provide a password.  Otherwise pass an empty string for the password.
    password = L"myPassword";
    success = CkPemW_LoadPemFile(pem,L"../myPemFiles/myPem.pem",password);
    if (success == FALSE) {
        wprintf(L"%s\n",CkPemW_lastErrorText(pem));
        CkPemW_Dispose(pem);
        return;
    }

    // Note: If the app already has the PEM pre-loaded in a string variable, then load it 
    // by calling LoadPem instead.  
    pemContent = L"... the PEM contents ...";
    success = CkPemW_LoadPem(pem,pemContent,password);
    // Check for success as before..

    // Iterate over the private keys.
    numPrivateKeys = CkPemW_getNumPrivateKeys(pem);
    i = 0;

    privKey = CkPrivateKeyW_Create();
    while (i < numPrivateKeys) {
        CkPemW_PrivateKeyAt(pem,i,privKey);
        wprintf(L"Private Key %d is %d in length\n",i,CkPrivateKeyW_getBitLength(privKey));
        i = i + 1;
    }

    // Iterate over the certificates.
    cert = CkCertW_Create();
    numCerts = CkPemW_getNumCerts(pem);
    i = 0;
    while (i < numCerts) {
        CkPemW_CertAt(pem,i,cert);
        wprintf(L"Certificate %d : %s\n",i,CkCertW_subjectDN(cert));
        i = i + 1;
    }



    CkPemW_Dispose(pem);
    CkPrivateKeyW_Dispose(privKey);
    CkCertW_Dispose(cert);

    }