Sample code for 30+ languages & platforms
C

Export a PKCS #8 Private Key as Encoded Text

See more Private Key Examples

Demonstrates the Chilkat PrivateKey.GetPkcs8ENC method, which exports the key as unencrypted PKCS #8 DER and encodes the DER bytes as text. The only argument names the binary encoding, such as base64 or hex.

Note: The file paths are relative to the application's current working directory. Absolute paths may also be used. Supply the paths appropriate to your own environment.

Background: DER is the compact binary form of a key; this method hands it back as encoded text so it can travel through channels that expect a string — a JSON field, a database column, a config value. It is the string-returning alternative to writing raw DER bytes, and choosing base64 versus hex is just a matter of what the consumer expects. The DER itself is unencrypted, so the encoded text is still sensitive.

Chilkat C Downloads

C
#include <C_CkPrivateKey.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkPrivateKey privKey;
    const char *encoded;

    success = FALSE;

    //  Load a private key to export.
    privKey = CkPrivateKey_Create();
    success = CkPrivateKey_LoadPemFile(privKey,"qa_data/private.pem");
    if (success == FALSE) {
        printf("%s\n",CkPrivateKey_lastErrorText(privKey));
        CkPrivateKey_Dispose(privKey);
        return;
    }

    //  Export as unencrypted PKCS #8 DER, then encode the DER bytes as text.  The only argument names
    //  the binary encoding, such as "base64" or "hex".
    encoded = CkPrivateKey_getPkcs8ENC(privKey,"base64");
    if (CkPrivateKey_getLastMethodSuccess(privKey) == FALSE) {
        printf("%s\n",CkPrivateKey_lastErrorText(privKey));
        CkPrivateKey_Dispose(privKey);
        return;
    }

    printf("%s\n",encoded);


    CkPrivateKey_Dispose(privKey);

    }