Sample code for 30+ languages & platforms
C

Save a Private Key as an Encrypted PKCS #8 DER File

See more Private Key Examples

Demonstrates the Chilkat PrivateKey.SavePkcs8EncryptedFile method, which saves the key as password-protected PKCS #8 DER. The first argument is the password and the second is the destination path. The cipher is selected by Pkcs8EncryptAlg.

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: This is the recommended way to persist a key to disk: the binary .der is encrypted under a passphrase, so a stolen file is useless without it. Reach for it whenever a key is stored or shipped. Choose the encryption cipher with Pkcs8EncryptAlg and source the password securely.

Chilkat C Downloads

C
#include <C_CkPrivateKey.h>

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

    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;
    }

    //  The key password is not hard-coded in a real application; obtain it from an interactive
    //  prompt, environment variable, or a secrets vault.
    password = "myKeyPassword";

    //  Save as password-protected PKCS #8 DER.  The 1st argument is the password and the 2nd is the
    //  destination path.  The cipher is selected by the Pkcs8EncryptAlg property.
    success = CkPrivateKey_SavePkcs8EncryptedFile(privKey,password,"qa_output/private_pkcs8_enc.der");
    if (success == FALSE) {
        printf("%s\n",CkPrivateKey_lastErrorText(privKey));
        CkPrivateKey_Dispose(privKey);
        return;
    }

    printf("Saved (encrypted).\n");


    CkPrivateKey_Dispose(privKey);

    }