Sample code for 30+ languages & platforms
C++

Get Public Key from CSR

See more CSR Examples

Demonstrates how to get the public key from a CSR.

Chilkat C++ Downloads

C++
#include <CkPem.h>
#include <CkAsn.h>
#include <CkXml.h>
#include <CkBinData.h>
#include <CkPublicKey.h>

void ChilkatSample(void)
    {
    bool success = false;

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

    CkPem pem;

    // No password is required.  Pass an empty password string..
    const char *noPassword = "";
    success = pem.LoadPemFile("qa_data/csr/csr2.pem",noPassword);
    if (success != true) {
        std::cout << pem.lastErrorText() << "\r\n";
        return;
    }

    const char *strBase64 = pem.getEncodedItem("csr","","base64",0);

    CkAsn asn;
    success = asn.LoadEncoded(strBase64,"base64");
    if (success != true) {
        std::cout << asn.lastErrorText() << "\r\n";
        return;
    }

    // Convert the ASN.1 to XML.
    CkXml xml;
    success = xml.LoadXml(asn.asnToXml());
    std::cout << xml.getXml() << "\r\n";
    std::cout << "----" << "\r\n";

    const char *strModulusHex = xml.getChildContent("bits");
    std::cout << "strModulusHex = " << strModulusHex << "\r\n";
    std::cout << "----" << "\r\n";

    // We need the modulus as base64.
    CkBinData bd;
    bd.AppendEncoded(strModulusHex,"hex");
    const char *modulus64 = bd.getEncoded("base64");
    std::cout << "modulus64 = " << modulus64 << "\r\n";
    std::cout << "----" << "\r\n";

    // Build the XML for the public key.
    CkXml xmlPubKey;
    xmlPubKey.put_Tag("RSAPublicKey");
    xmlPubKey.UpdateChildContent("Modulus",modulus64);
    // The RSA exponent will always be decimal 65537 (base64 = AQAB)
    xmlPubKey.UpdateChildContent("Exponent","AQAB");

    std::cout << "RSA public key as XML:" << "\r\n";
    std::cout << xmlPubKey.getXml() << "\r\n";
    std::cout << "----" << "\r\n";

    // Load the XML into a Chilkat public key object.
    CkPublicKey pubkey;
    success = pubkey.LoadFromString(xmlPubKey.getXml());
    if (success != true) {
        std::cout << pubkey.lastErrorText() << "\r\n";
        return;
    }

    // Show the public key as PEM.
    bool preferPkcs1 = true;
    std::cout << pubkey.getPem(preferPkcs1) << "\r\n";
    }