Contents · Forum Home · StreamSec Tools 4.1.5.365 documentation

Sign a file and verify its detached CMS signature

A detached signature travels separately from the file it signs. Give the recipient both files, for example report.pdf and report.pdf.p7s. The recipient verifies the original bytes, including any line endings.

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.

Sign the file

Use an enabled TstCertificateManager containing the signer's certificate and matching RSA private key. Its public-key index lets the component find the private key for the certificate you pass. The private key stays with the signer. The units below link the RSA and SHA-256 implementations.

uses
  System.SysUtils, System.Classes, stSecUtils, stSHA256, stDrbgAesCtr,
  stGC, stOIDs, stDERCoder, StreamSec.DSI.Arith, StreamSec.DSI.IFC,
  StreamSec.DSI.PkixCert, StreamSec.DSI.PkixKeyManager,
  StreamSec.DSI.CMS, StreamSec.DSI.PkixCms;
function SignDetachedFile(aKeys: TstCertificateManager; const aSigner: iCertificate;
  const aFileName, aSignatureFile: string): Boolean;
var
  lSigner: TstMPSignedData;
  lContent: 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;
    lContent := TFileStream.Create(aFileName, fmOpenRead or fmShareDenyWrite);
    try
      lSignature := TMemoryStream.Create;
      try
        Result := lSigner.SignData(aSigner, lContent, lSignature);
        if Result then lSignature.SaveToFile(aSignatureFile);
      finally
        lSignature.Free;
      end;
    finally
      lContent.Free;
    end;
  finally
    lSigner.Free;
  end;
end;

Pass the file to sign and a separate output path for the signature. The function writes the DER-encoded CMS signature when signing succeeds.

Verify the signer's identity and the file

Obtain the expected signer's certificate from a trusted source and check its validity, signing usage and your revocation policy. Check a certificate chain and its revocation shows the chain check. A certificate carried in the signature is a claim about the signer. Choose the expected certificate independently.

Configure the verifier's certificate manager with the trusted certificates, a chain filter and an issuer-and-serial CMS index (tKeyIndexSerialIssuerCMS) covering the signer. The verifier needs only the public certificate. This example accepts DER CMS with one signer and detached file content. It checks that format before giving the component the original file to hash.

function IsDetachedFileSignature(aSignature: TStream): Boolean;
var
  lInfo: iContentInfo;
  lSigned: iSignedData;
begin
  lInfo := tContentInfo.Create(gcamFirstAssignment);
  lInfo.GetStruct.LoadFromStream(aSignature, fmtDER);
  if lInfo.contentType <> id_signedData then Exit(False);
  lSigned := lInfo.content.AsSignedData;
  Result := (lSigned.encapContentInfo.eContentType = id_data) and
            ((lSigned.encapContentInfo.eContent = nil) or
             not lSigned.encapContentInfo.eContent.GetStruct.Present) and
            (lSigned.signerInfos.ItemCount = 1);
  aSignature.Position := 0;
end;

type
  tExpectedSigner = class
    Certificate: iCertificate;
    Matched: Boolean;
    procedure GoodSignature(Sender: TObject; aSignerCert: iCertificate);
  end;

procedure tExpectedSigner.GoodSignature(Sender: TObject; aSignerCert: iCertificate);
begin
  Matched := Certificate.SameCert(aSignerCert);
end;
function VerifyDetachedFile(aKeys: TstCertificateManager; const aExpectedSigner: iCertificate;
  const aFileName, aSignatureFile: string): Boolean;
var
  lVerifier: TstMPSignedData;
  lExpected: tExpectedSigner;
  lContent, lSignature: TFileStream;
begin
  Result := False;
  if (aKeys = nil) or (aExpectedSigner = nil) then Exit;
  lSignature := TFileStream.Create(aSignatureFile, fmOpenRead or fmShareDenyWrite);
  try
    if not IsDetachedFileSignature(lSignature) then Exit;
    lContent := TFileStream.Create(aFileName, fmOpenRead or fmShareDenyWrite);
    try
      lVerifier := TstMPSignedData.Create(nil);
      try
        lExpected := tExpectedSigner.Create;
        try
          lExpected.Certificate := aExpectedSigner;
          lVerifier.KeysAndCerts := aKeys;
          lVerifier.AllowExpiredCertificates := False;
          lVerifier.OnGoodSignature := lExpected.GoodSignature;
          Result := lVerifier.VerifySignedData(lSignature, lContent) and lExpected.Matched;
        finally
          lExpected.Free;
        end;
      finally
        lVerifier.Free;
      end;
    finally
      lContent.Free;
    end;
  finally
    lSignature.Free;
  end;
end;

Pass the original file, the signature file and the certificate you expect. True means both the signature and the signer's certificate matched. A modified file, an attached message or a signature from a different trusted signer gives False. An unreadable file or malformed ASN.1 can raise an exception. Treat either failure as an unverified file.

The PKIX notes describe CMS signer identifiers, algorithms and countersignatures.

Reference

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

Related tasks