Sample code for 30+ languages & platforms
C

Export a Public Key as PEM

Demonstrates the Chilkat PublicKey.GetPem method, which returns the public key in PEM format. The only argument selects the underlying DER representation: true prefers the traditional PKCS #1 form (RSA), false uses the SubjectPublicKeyInfo form.

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: PEM is the most portable way to share a public key — the Base64 text block most tooling reads. The boolean picks the encoding: false produces the modern, algorithm-independent PUBLIC KEY (SubjectPublicKeyInfo), which is the usual choice; true produces the older RSA-specific RSA PUBLIC KEY for tools that require it. A public key is not sensitive, so the PEM can be distributed openly.

Chilkat C Downloads

C
#include <C_CkPublicKey.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkPublicKey pubKey;
    BOOL preferPkcs1;
    const char *pem;

    success = FALSE;

    //  Load a public key to export.  LoadFromFile inspects the content, so it accepts DER, PEM, XML,
    //  JWK, and other supported representations.
    pubKey = CkPublicKey_Create();
    success = CkPublicKey_LoadFromFile(pubKey,"qa_data/public.pem");
    if (success == FALSE) {
        printf("%s\n",CkPublicKey_lastErrorText(pubKey));
        CkPublicKey_Dispose(pubKey);
        return;
    }

    //  Export the public key in PEM format.  The argument selects the underlying DER representation:
    //  TRUE prefers the traditional PKCS #1 form (RSA), FALSE uses the SubjectPublicKeyInfo form.
    preferPkcs1 = FALSE;
    pem = CkPublicKey_getPem(pubKey,preferPkcs1);
    if (CkPublicKey_getLastMethodSuccess(pubKey) == FALSE) {
        printf("%s\n",CkPublicKey_lastErrorText(pubKey));
        CkPublicKey_Dispose(pubKey);
        return;
    }

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


    CkPublicKey_Dispose(pubKey);

    }