A certificate file is either DER (binary) or PEM (text between -----BEGIN CERTIFICATE----- lines). tCertificate reads both and gives access to every field.
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
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;
ExpandFull after loading, before reading fields: a certificate is decoded on demand, and expanding it once decodes all of it.dNSName entries; the Web PKI no longer treats the subject's common name as an identity. To ask whether a certificate covers one name, call CheckDNSName. It compares the name case-insensitively with every dNSName entry and with every common name in the subject, also when the certificate has dNSName entries. A wildcard entry *.example.com matches www.example.com and also names deeper down, such as a.b.example.com; it does not match example.com itself. RFC 9525 section 6.3 lets a wildcard match one label only, so where that rule matters, check the left-most label yourself.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.