Sample code for 30+ languages & platforms
AutoIt

Get Public Key from CSR

See more CSR Examples

Demonstrates how to get the public key from a CSR.

Chilkat AutoIt Downloads

AutoIt
Local $bSuccess = False

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

$oPem = ObjCreate("Chilkat.Pem")

; No password is required.  Pass an empty password string..
Local $sNoPassword = ""
$bSuccess = $oPem.LoadPemFile("qa_data/csr/csr2.pem",$sNoPassword)
If ($bSuccess <> True) Then
    ConsoleWrite($oPem.LastErrorText & @CRLF)
    Exit
EndIf

Local $strBase64 = $oPem.GetEncodedItem("csr","","base64",0)

$oAsn = ObjCreate("Chilkat.Asn")
$bSuccess = $oAsn.LoadEncoded($strBase64,"base64")
If ($bSuccess <> True) Then
    ConsoleWrite($oAsn.LastErrorText & @CRLF)
    Exit
EndIf

; Convert the ASN.1 to XML.
$oXml = ObjCreate("Chilkat.Xml")
$bSuccess = $oXml.LoadXml($oAsn.AsnToXml())
ConsoleWrite($oXml.GetXml() & @CRLF)
ConsoleWrite("----" & @CRLF)

Local $strModulusHex = $oXml.GetChildContent("bits")
ConsoleWrite("strModulusHex = " & $strModulusHex & @CRLF)
ConsoleWrite("----" & @CRLF)

; We need the modulus as base64.
$oBd = ObjCreate("Chilkat.BinData")
$oBd.AppendEncoded($strModulusHex,"hex")
Local $sModulus64 = $oBd.GetEncoded("base64")
ConsoleWrite("modulus64 = " & $sModulus64 & @CRLF)
ConsoleWrite("----" & @CRLF)

; Build the XML for the public key.
$oXmlPubKey = ObjCreate("Chilkat.Xml")
$oXmlPubKey.Tag = "RSAPublicKey"
$oXmlPubKey.UpdateChildContent "Modulus",$sModulus64
; The RSA exponent will always be decimal 65537 (base64 = AQAB)
$oXmlPubKey.UpdateChildContent "Exponent","AQAB"

ConsoleWrite("RSA public key as XML:" & @CRLF)
ConsoleWrite($oXmlPubKey.GetXml() & @CRLF)
ConsoleWrite("----" & @CRLF)

; Load the XML into a Chilkat public key object.
$oPubkey = ObjCreate("Chilkat.PublicKey")
$bSuccess = $oPubkey.LoadFromString($oXmlPubKey.GetXml())
If ($bSuccess <> True) Then
    ConsoleWrite($oPubkey.LastErrorText & @CRLF)
    Exit
EndIf

; Show the public key as PEM.
Local $bPreferPkcs1 = True
ConsoleWrite($oPubkey.GetPem($bPreferPkcs1) & @CRLF)