Contents · Forum Home · StreamSec Tools 4.1.5.365 documentation

Create and verify a CAdES baseline signature for a file

A detached CAdES signature lets the recipient check a file against its original bytes and the certificate the signer used. Send the file and its signature together, for example report.bin and report.p7s.

The components on this page are normally placed on a form or a data module at design time and set up in the Object Inspector. The sample creates them in code instead, because code shows at a glance which properties are changed from their default values.

Create a B-B signature

uses
  System.Classes, System.SysUtils, stDERUtils, stDERCoder, stGC, stOIDs,
  stSecUtils, stSHA256, stDrbgAesCtr, StreamSec.DSI.Arith, StreamSec.DSI.IFC,
  StreamSec.DSI.PkixCert, StreamSec.DSI.PkixKeyManager, StreamSec.DSI.CMS,
  StreamSec.DSI.PkixCms, StreamSec.DSI.CAdES;

Supply a certificate manager containing the signing certificate and its matching RSA private key. See Sign a file and verify its detached CMS signature for the certificate manager and key indexes. Give the signature its own output path.

function SignCadesFile(aKeys: TstCertificateManager; const aSigner: iCertificate;
  const aFileName, aSignatureFile: string): Boolean;
var
  lSigner: TstMPSignedData;
  lFile: TFileStream;
  lSignature: TMemoryStream;
begin
  Result := False;
  if (aKeys = nil) or (aSigner = nil) then Exit;
  lSigner := TstMPSignedData.Create(nil);
  try
    lSigner.KeysAndCerts := aKeys;
    lSigner.DetachedSignature := True;
    lSigner.ContentDigestAlg := haSHA256;
    lSigner.IncludeSigningTime := True;
    lSigner.IncludeSigningCertificateV2 := True;
    lFile := TFileStream.Create(aFileName, fmOpenRead or fmShareDenyWrite);
    try
      lSignature := TMemoryStream.Create;
      try
        if not lSigner.SignData(aSigner, lFile, lSignature) then Exit;
        if CAdESLevelOf(lSignature) <> calBB then Exit;
        lSignature.SaveToFile(aSignatureFile);
        Result := True;
      finally
        lSignature.Free;
      end;
    finally
      lFile.Free;
    end;
  finally
    lSigner.Free;
  end;
end;

IncludeSigningCertificateV2 puts the SHA-256 hash of the signing certificate in the signed attributes. The signature covers that reference as well as the file digest. The signing time is the signer's own clock. The function reads back the emitted signature with CAdESLevelOf and saves it once the library reports calBB.

Check the reference to the expected certificate

Obtain the expected signing certificate independently of the signature. Configure a public-only certificate manager with the appropriate trust anchors, certificate filter and issuer-and-serial CMS index. Apply your certificate chain and revocation policy.

function HasExpectedBinding(aSignature: TStream; const aCertificate: iCertificate): Boolean;
const
  cSigningCertificateV2 = '1.2.840.113549.1.9.16.2.47';
  // DER: SigningCertificateV2, certs, ESSCertIDv2, 32-byte SHA-256 hash.
  cReferencePrefix: OctetString = #$30#$26#$30#$24#$30#$22#$04#$20;
var
  lInfo: iContentInfo;
  lSigned: iSignedData;
  lSigner: iSignerInfo;
  lAttr: iSignedAttribute;
  lReference: OctetString;
  i: Integer;
begin
  Result := False;
  aSignature.Position := 0;
  lInfo := tContentInfo.Create(gcamFirstAssignment);
  lInfo.GetStruct.LoadFromStream(aSignature, fmtDER);
  if lInfo.contentType <> id_signedData then Exit;
  lSigned := lInfo.content.AsSignedData;
  if (lSigned.encapContentInfo.eContentType <> id_data) or
     ((lSigned.encapContentInfo.eContent <> nil) and
      lSigned.encapContentInfo.eContent.GetStruct.Present) or
     (lSigned.signerInfos.ItemCount <> 1) then Exit;
  lSigner := lSigned.signerInfos[0];
  if lSigner.digestAlgorithm.algorithm <> id_sha256 then Exit;
  lReference := cReferencePrefix + DigestString(haSHA256,
    aCertificate.GetStruct.EncodedContentsOS(tDERCoder.DefaultCoder, True));
  for i := 0 to lSigner.signedAttrs.ItemCount - 1 do begin
    lAttr := lSigner.signedAttrs.Items[i];
    if lAttr.attrType <> cSigningCertificateV2 then Continue;
    if Result or (lAttr.attrValuesCount <> 1) then Exit(False);
    if lAttr.attrValues[0].GetStruct.EncodedContentsOS(tDERCoder.DefaultCoder, True)
        <> lReference then Exit(False);
    Result := True;
  end;
end;

The first certificate reference in signingCertificateV2 identifies the signer. The component writes one reference, with SHA-256 as the default digest and the optional issuer and serial number omitted. The sample checks exactly that encoding. A producer that includes optional fields or additional certificate references needs a verifier that decodes those forms. The comparison uses the DER bytes of the whole expected certificate.

Verify the original bytes and read the baseline level

type
  tCadesSignerCheck = class
    Expected: iCertificate;
    Matched: Boolean;
    procedure GoodSignature(Sender: TObject; aSigner: iCertificate);
  end;

procedure tCadesSignerCheck.GoodSignature(Sender: TObject; aSigner: iCertificate);
begin
  Matched := Expected.SameCert(aSigner);
end;

function VerifyCadesStreams(aKeys: TstCertificateManager; const aExpectedSigner: iCertificate;
  aContent, aSignature: TStream; out aLevel: tCAdESLevel): Boolean;
var
  lVerify: TstMPSignedData;
  lSigner: tCadesSignerCheck;
begin
  Result := False;
  aLevel := calNone;
  if (aKeys = nil) or (aExpectedSigner = nil) or
     (aContent = nil) or (aSignature = nil) then Exit;
  if not HasExpectedBinding(aSignature, aExpectedSigner) then Exit;
  lVerify := TstMPSignedData.Create(nil);
  try
    lSigner := tCadesSignerCheck.Create;
    try
      lSigner.Expected := aExpectedSigner;
      lVerify.KeysAndCerts := aKeys;
      lVerify.AllowExpiredCertificates := False;
      lVerify.OnGoodSignature := lSigner.GoodSignature;
      aContent.Position := 0;
      aSignature.Position := 0;
      if not lVerify.VerifySignedData(aSignature, aContent) then Exit;
      if not lSigner.Matched then Exit;
      aLevel := CAdESLevelOf(aSignature);
      Result := aLevel >= calBB;
    finally
      lSigner.Free;
    end;
  finally
    lVerify.Free;
  end;
end;

VerifySignedData checks the detached file against the signature. OnGoodSignature supplies the certificate used in that check. The sample requires it to match the expected certificate before returning the level read from the signature. Level detection identifies attributes present in the file. A damaged signed attribute can still be classified as calBB.

function VerifyCadesFile(aKeys: TstCertificateManager; const aExpectedSigner: iCertificate;
  const aFileName, aSignatureFile: string; out aLevel: tCAdESLevel): Boolean;
var
  lContent, lSignature: TFileStream;
begin
  lContent := TFileStream.Create(aFileName, fmOpenRead or fmShareDenyWrite);
  try
    lSignature := TFileStream.Create(aSignatureFile, fmOpenRead or fmShareDenyWrite);
    try
      Result := VerifyCadesStreams(aKeys, aExpectedSigner, lContent, lSignature, aLevel);
    finally
      lSignature.Free;
    end;
  finally
    lContent.Free;
  end;
end;

Pass the original file path, the detached signature path and the expected certificate to VerifyCadesFile. For a file just signed by this example, check for both a True result and aLevel = calBB. The stream version accepts seekable streams positioned anywhere and reads them from the start. A False result or an exception leaves the file unverified. A higher reported level identifies additional attributes. A relying party still needs to validate the timestamp and revocation evidence for its intended use.

Reference

TstMPSignedData · TstCertificateManager · StreamSec.DSI.PkixCms · StreamSec.DSI.PkixKeyManager · StreamSec.DSI.CAdES · StreamSec.DSI.CMS

Related tasks