Sample code for 30+ languages & platforms
Unicode C++

Get the Public Key from a Private Key

See more Private Key Examples

Demonstrates the Chilkat PrivateKey.ToPublicKey method, which extracts the public portion of the loaded private key into an independent PublicKey object. The only argument is the PublicKey that receives the copy.

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: A key pair's public half is derived from the private half, and this is how you obtain it — the public key you distribute for others to verify signatures or encrypt to you, while the private key stays secret. The resulting PublicKey is an independent copy, so exporting or sharing it never risks exposing the private material. From there, export it as PEM, JWK, or XML as needed.

Chilkat Unicode C++ Downloads

Unicode C++
#include <CkPrivateKeyW.h>
#include <CkPublicKeyW.h>

void ChilkatSample(void)
    {
    bool success = false;

    //  Load a private key to export.
    CkPrivateKeyW privKey;
    success = privKey.LoadPemFile(L"qa_data/private.pem");
    if (success == false) {
        wprintf(L"%s\n",privKey.lastErrorText());
        return;
    }

    //  Extract the public portion of the private key into an independent PublicKey object.  The
    //  PublicKey is a separate copy, unaffected by later changes to the PrivateKey.
    CkPublicKeyW pubKey;
    success = privKey.ToPublicKey(pubKey);
    if (success == false) {
        wprintf(L"%s\n",privKey.lastErrorText());
        return;
    }

    //  The PublicKey can now be exported or shared -- for example as PEM.  The argument prefers the
    //  traditional PKCS #1 PEM when a traditional representation exists.
    bool preferPkcs1 = true;
    const wchar_t *pubPem = pubKey.getPem(preferPkcs1);
    if (pubKey.get_LastMethodSuccess() == false) {
        wprintf(L"%s\n",pubKey.lastErrorText());
        return;
    }

    wprintf(L"%s\n",pubPem);
    }