Sample code for 30+ languages & platforms
Delphi DLL

Get Public Key from CSR

See more CSR Examples

Demonstrates how to get the public key from a CSR.

Chilkat Delphi DLL Downloads

Delphi DLL
uses
    Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
    Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, BinData, Asn, PublicKey, Xml, Pem;

...

procedure TForm1.Button1Click(Sender: TObject);
var
success: Boolean;
pem: HCkPem;
noPassword: PWideChar;
strBase64: PWideChar;
asn: HCkAsn;
xml: HCkXml;
strModulusHex: PWideChar;
bd: HCkBinData;
modulus64: PWideChar;
xmlPubKey: HCkXml;
pubkey: HCkPublicKey;
preferPkcs1: Boolean;

begin
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) then
  begin
    Memo1.Lines.Add(CkPem__lastErrorText(pem));
    Exit;
  end;

strBase64 := CkPem__getEncodedItem(pem,'csr','','base64',0);

asn := CkAsn_Create();
success := CkAsn_LoadEncoded(asn,strBase64,'base64');
if (success <> True) then
  begin
    Memo1.Lines.Add(CkAsn__lastErrorText(asn));
    Exit;
  end;

// Convert the ASN.1 to XML.
xml := CkXml_Create();
success := CkXml_LoadXml(xml,CkAsn__asnToXml(asn));
Memo1.Lines.Add(CkXml__getXml(xml));
Memo1.Lines.Add('----');

strModulusHex := CkXml__getChildContent(xml,'bits');
Memo1.Lines.Add('strModulusHex = ' + strModulusHex);
Memo1.Lines.Add('----');

// We need the modulus as base64.
bd := CkBinData_Create();
CkBinData_AppendEncoded(bd,strModulusHex,'hex');
modulus64 := CkBinData__getEncoded(bd,'base64');
Memo1.Lines.Add('modulus64 = ' + modulus64);
Memo1.Lines.Add('----');

// 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');

Memo1.Lines.Add('RSA public key as XML:');
Memo1.Lines.Add(CkXml__getXml(xmlPubKey));
Memo1.Lines.Add('----');

// Load the XML into a Chilkat public key object.
pubkey := CkPublicKey_Create();
success := CkPublicKey_LoadFromString(pubkey,CkXml__getXml(xmlPubKey));
if (success <> True) then
  begin
    Memo1.Lines.Add(CkPublicKey__lastErrorText(pubkey));
    Exit;
  end;

// Show the public key as PEM.
preferPkcs1 := True;
Memo1.Lines.Add(CkPublicKey__getPem(pubkey,preferPkcs1));

CkPem_Dispose(pem);
CkAsn_Dispose(asn);
CkXml_Dispose(xml);
CkBinData_Dispose(bd);
CkXml_Dispose(xmlPubKey);
CkPublicKey_Dispose(pubkey);

end;