C
C
Get Public Key from CSR
See more CSR Examples
Demonstrates how to get the public key from a CSR.Chilkat C Downloads
#include <C_CkPem.h>
#include <C_CkAsn.h>
#include <C_CkXml.h>
#include <C_CkBinData.h>
#include <C_CkPublicKey.h>
void ChilkatSample(void)
{
BOOL success;
HCkPem pem;
const char *noPassword;
const char *strBase64;
HCkAsn asn;
HCkXml xml;
const char *strModulusHex;
HCkBinData bd;
const char *modulus64;
HCkXml xmlPubKey;
HCkPublicKey pubkey;
BOOL preferPkcs1;
success = FALSE;
// This requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
pem = CkPem_Create();
// No password is required. Pass an empty password string..
noPassword = "";
success = CkPem_LoadPemFile(pem,"qa_data/csr/csr2.pem",noPassword);
if (success != TRUE) {
printf("%s\n",CkPem_lastErrorText(pem));
CkPem_Dispose(pem);
return;
}
strBase64 = CkPem_getEncodedItem(pem,"csr","","base64",0);
asn = CkAsn_Create();
success = CkAsn_LoadEncoded(asn,strBase64,"base64");
if (success != TRUE) {
printf("%s\n",CkAsn_lastErrorText(asn));
CkPem_Dispose(pem);
CkAsn_Dispose(asn);
return;
}
// Convert the ASN.1 to XML.
xml = CkXml_Create();
success = CkXml_LoadXml(xml,CkAsn_asnToXml(asn));
printf("%s\n",CkXml_getXml(xml));
printf("----\n");
strModulusHex = CkXml_getChildContent(xml,"bits");
printf("strModulusHex = %s\n",strModulusHex);
printf("----\n");
// We need the modulus as base64.
bd = CkBinData_Create();
CkBinData_AppendEncoded(bd,strModulusHex,"hex");
modulus64 = CkBinData_getEncoded(bd,"base64");
printf("modulus64 = %s\n",modulus64);
printf("----\n");
// Build the XML for the public key.
xmlPubKey = CkXml_Create();
CkXml_putTag(xmlPubKey,"RSAPublicKey");
CkXml_UpdateChildContent(xmlPubKey,"Modulus",modulus64);
// The RSA exponent will always be decimal 65537 (base64 = AQAB)
CkXml_UpdateChildContent(xmlPubKey,"Exponent","AQAB");
printf("RSA public key as XML:\n");
printf("%s\n",CkXml_getXml(xmlPubKey));
printf("----\n");
// Load the XML into a Chilkat public key object.
pubkey = CkPublicKey_Create();
success = CkPublicKey_LoadFromString(pubkey,CkXml_getXml(xmlPubKey));
if (success != TRUE) {
printf("%s\n",CkPublicKey_lastErrorText(pubkey));
CkPem_Dispose(pem);
CkAsn_Dispose(asn);
CkXml_Dispose(xml);
CkBinData_Dispose(bd);
CkXml_Dispose(xmlPubKey);
CkPublicKey_Dispose(pubkey);
return;
}
// Show the public key as PEM.
preferPkcs1 = TRUE;
printf("%s\n",CkPublicKey_getPem(pubkey,preferPkcs1));
CkPem_Dispose(pem);
CkAsn_Dispose(asn);
CkXml_Dispose(xml);
CkBinData_Dispose(bd);
CkXml_Dispose(xmlPubKey);
CkPublicKey_Dispose(pubkey);
}