Sample code for 30+ languages & platforms
Lianja

Get Public Key from CSR

See more CSR Examples

Demonstrates how to get the public key from a CSR.

Chilkat Lianja Downloads

Lianja
llSuccess = .F.

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

loPem = createobject("CkPem")

// No password is required.  Pass an empty password string..
lcNoPassword = ""
llSuccess = loPem.LoadPemFile("qa_data/csr/csr2.pem",lcNoPassword)
if (llSuccess <> .T.) then
    ? loPem.LastErrorText
    release loPem
    return
endif

lcStrBase64 = loPem.GetEncodedItem("csr","","base64",0)

loAsn = createobject("CkAsn")
llSuccess = loAsn.LoadEncoded(lcStrBase64,"base64")
if (llSuccess <> .T.) then
    ? loAsn.LastErrorText
    release loPem
    release loAsn
    return
endif

// Convert the ASN.1 to XML.
loXml = createobject("CkXml")
llSuccess = loXml.LoadXml(loAsn.AsnToXml())
? loXml.GetXml()
? "----"

lcStrModulusHex = loXml.GetChildContent("bits")
? "strModulusHex = " + lcStrModulusHex
? "----"

// We need the modulus as base64.
loBd = createobject("CkBinData")
loBd.AppendEncoded(lcStrModulusHex,"hex")
lcModulus64 = loBd.GetEncoded("base64")
? "modulus64 = " + lcModulus64
? "----"

// Build the XML for the public key.
loXmlPubKey = createobject("CkXml")
loXmlPubKey.Tag = "RSAPublicKey"
loXmlPubKey.UpdateChildContent("Modulus",lcModulus64)
// The RSA exponent will always be decimal 65537 (base64 = AQAB)
loXmlPubKey.UpdateChildContent("Exponent","AQAB")

? "RSA public key as XML:"
? loXmlPubKey.GetXml()
? "----"

// Load the XML into a Chilkat public key object.
loPubkey = createobject("CkPublicKey")
llSuccess = loPubkey.LoadFromString(loXmlPubKey.GetXml())
if (llSuccess <> .T.) then
    ? loPubkey.LastErrorText
    release loPem
    release loAsn
    release loXml
    release loBd
    release loXmlPubKey
    release loPubkey
    return
endif

// Show the public key as PEM.
llPreferPkcs1 = .T.
? loPubkey.GetPem(llPreferPkcs1)


release loPem
release loAsn
release loXml
release loBd
release loXmlPubKey
release loPubkey