Unicode C++
Unicode C++
Get Public Key from CSR
See more CSR Examples
Demonstrates how to get the public key from a CSR.Chilkat Unicode C++ Downloads
#include <CkPemW.h>
#include <CkAsnW.h>
#include <CkXmlW.h>
#include <CkBinDataW.h>
#include <CkPublicKeyW.h>
void ChilkatSample(void)
{
bool success = false;
// This requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
CkPemW pem;
// No password is required. Pass an empty password string..
const wchar_t *noPassword = L"";
success = pem.LoadPemFile(L"qa_data/csr/csr2.pem",noPassword);
if (success != true) {
wprintf(L"%s\n",pem.lastErrorText());
return;
}
const wchar_t *strBase64 = pem.getEncodedItem(L"csr",L"",L"base64",0);
CkAsnW asn;
success = asn.LoadEncoded(strBase64,L"base64");
if (success != true) {
wprintf(L"%s\n",asn.lastErrorText());
return;
}
// Convert the ASN.1 to XML.
CkXmlW xml;
success = xml.LoadXml(asn.asnToXml());
wprintf(L"%s\n",xml.getXml());
wprintf(L"----\n");
const wchar_t *strModulusHex = xml.getChildContent(L"bits");
wprintf(L"strModulusHex = %s\n",strModulusHex);
wprintf(L"----\n");
// We need the modulus as base64.
CkBinDataW bd;
bd.AppendEncoded(strModulusHex,L"hex");
const wchar_t *modulus64 = bd.getEncoded(L"base64");
wprintf(L"modulus64 = %s\n",modulus64);
wprintf(L"----\n");
// Build the XML for the public key.
CkXmlW xmlPubKey;
xmlPubKey.put_Tag(L"RSAPublicKey");
xmlPubKey.UpdateChildContent(L"Modulus",modulus64);
// The RSA exponent will always be decimal 65537 (base64 = AQAB)
xmlPubKey.UpdateChildContent(L"Exponent",L"AQAB");
wprintf(L"RSA public key as XML:\n");
wprintf(L"%s\n",xmlPubKey.getXml());
wprintf(L"----\n");
// Load the XML into a Chilkat public key object.
CkPublicKeyW pubkey;
success = pubkey.LoadFromString(xmlPubKey.getXml());
if (success != true) {
wprintf(L"%s\n",pubkey.lastErrorText());
return;
}
// Show the public key as PEM.
bool preferPkcs1 = true;
wprintf(L"%s\n",pubkey.getPem(preferPkcs1));
}