Contents · Forum Home · StreamSec Tools 4.1.5.364 documentation

Read a certificate file

A certificate file is either DER (binary) or PEM (text between -----BEGIN CERTIFICATE----- lines). tCertificate reads both and gives access to every field.

The units

uses
  System.SysUtils, System.Classes, System.IOUtils,

  stGC,                            // gcamFirstAssignment
  stASN1Base, stDERCoder, stPEMCoder,  // LoadFromFile, SaveToFile: fmtDER, fmtPEM
  stPkixExtension, stPkixGeneralName,  // evCeSubjectAltName, gnDNSName
  StreamSec.DSI.Arith, StreamSec.DSI.ECArith, StreamSec.DSI.IFC,
  StreamSec.DSI.PkixCert,          // tCertificate, iCertificate
  StreamSec.DSI.PkixCRL,           // tCertificateList
  StreamSec.DSI.Ocsp,              // TRevocationPolicy
  StreamSec.Mobile.X509Comp;       // TsmX509TrustedCertificates

Load and read

function LoadCertificate(const aFileName: string): iCertificate;
var
  lHead: string;
begin
  { A certificate file is DER (binary) or PEM (text beginning -----BEGIN). }
  lHead := TFile.ReadAllText(aFileName, TEncoding.ANSI).Substring(0, 11);
  Result := tCertificate.Create(gcamFirstAssignment);
  if lHead = '-----BEGIN ' then
    Result.GetStruct.LoadFromFile(aFileName, fmtPEM)
  else
    Result.GetStruct.LoadFromFile(aFileName, fmtDER);
  { Decode every field now, before any is read. }
  Result.GetStruct.ExpandFull;
end;

procedure DescribeCertificate(const aCert: iCertificate; aLines: TStrings);
var
  lExt: iExtension;
  I: Integer;
begin
  with aCert.tbsCertificate do begin
    aLines.Add('Subject CN: ' + subject.AsRdnSequence.CommonName);
    aLines.Add('Issuer CN:  ' + issuer.AsRdnSequence.CommonName);
    aLines.Add('Valid from: ' + DateTimeToStr(validity.notBefore.AsDateTime));
    aLines.Add('Valid to:   ' + DateTimeToStr(validity.notAfter.AsDateTime));
    { The names the certificate is valid for are its subjectAltName
      dNSName entries. }
    lExt := extensions.FindExtension(evCeSubjectAltName);
    if Assigned(lExt) then
      for I := 0 to lExt.extnValue.AsCeSubjectAltName.ItemCount - 1 do
        if lExt.extnValue.AsCeSubjectAltName.Items[I].Choice = gnDNSName then
          aLines.Add('DNS name:   ' + lExt.extnValue.AsCeSubjectAltName.Items[I].AsDnsname);
  end;
end;

A certificate together with its private key - for a server - comes in a PFX file, which the TLS engine reads with ImportFromPFX: see Serve HTTPS from a PFX file.

Reference

StreamSec.DSI.PkixCert

Related tasks