Pascal (Lazarus/Delphi)
Pascal (Lazarus/Delphi)
Get Public Key from CSR
See more CSR Examples
Demonstrates how to get the public key from a CSR.Chilkat Pascal (Lazarus/Delphi) Downloads
program ChilkatDemo;
// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}
uses
{$IFDEF UNIX}
cthreads,
{$ENDIF}
SysUtils,
CkDllLoader,
Chilkat.BinData,
Chilkat.Asn,
Chilkat.PublicKey,
Chilkat.Xml,
Chilkat.Pem;
// ---------------------------------------------------------------------------
procedure RunDemo;
var
success: Boolean;
pem: TPem;
noPassword: string;
strBase64: string;
asn: TAsn;
xml: TXml;
strModulusHex: string;
bd: TBinData;
modulus64: string;
xmlPubKey: TXml;
pubkey: TPublicKey;
preferPkcs1: Boolean;
begin
success := False;
// This requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
pem := TPem.Create;
// No password is required. Pass an empty password string..
noPassword := '';
success := pem.LoadPemFile('qa_data/csr/csr2.pem',noPassword);
if (success <> True) then
begin
WriteLn(pem.LastErrorText);
Exit;
end;
strBase64 := pem.GetEncodedItem('csr','','base64',0);
asn := TAsn.Create;
success := asn.LoadEncoded(strBase64,'base64');
if (success <> True) then
begin
WriteLn(asn.LastErrorText);
Exit;
end;
// Convert the ASN.1 to XML.
xml := TXml.Create;
success := xml.LoadXml(asn.AsnToXml());
WriteLn(xml.GetXml());
WriteLn('----');
strModulusHex := xml.GetChildContent('bits');
WriteLn('strModulusHex = ' + strModulusHex);
WriteLn('----');
// We need the modulus as base64.
bd := TBinData.Create;
bd.AppendEncoded(strModulusHex,'hex');
modulus64 := bd.GetEncoded('base64');
WriteLn('modulus64 = ' + modulus64);
WriteLn('----');
// Build the XML for the public key.
xmlPubKey := TXml.Create;
xmlPubKey.Tag := 'RSAPublicKey';
xmlPubKey.UpdateChildContent('Modulus',modulus64);
// The RSA exponent will always be decimal 65537 (base64 = AQAB)
xmlPubKey.UpdateChildContent('Exponent','AQAB');
WriteLn('RSA public key as XML:');
WriteLn(xmlPubKey.GetXml());
WriteLn('----');
// Load the XML into a Chilkat public key object.
pubkey := TPublicKey.Create;
success := pubkey.LoadFromString(xmlPubKey.GetXml());
if (success <> True) then
begin
WriteLn(pubkey.LastErrorText);
Exit;
end;
// Show the public key as PEM.
preferPkcs1 := True;
WriteLn(pubkey.GetPem(preferPkcs1));
pem.Free;
asn.Free;
xml.Free;
bd.Free;
xmlPubKey.Free;
pubkey.Free;
end;
// ---------------------------------------------------------------------------
begin
try
RunDemo;
except
on E: Exception do
WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
end;
WriteLn;
{$IFDEF MSWINDOWS}
WriteLn('Press Enter to exit...');
ReadLn;
{$ENDIF}
end.