Contents · Forum Home · StreamSec Tools 4.1.5.365 documentation

Sign and verify an S/MIME message

Sign the MIME body and its Content-* headers, save the resulting multipart/signed message as an .eml file, and verify it after reading it back. The clear first part remains readable by ordinary mail clients. Attachments inside that part are covered by the signature. The outer From, To and Subject headers remain editable.

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.

Prepare the signer and verifier

uses
  System.SysUtils, stSecUtils, stSHA256, stDrbgAesCtr, stAESCT, stAESNI,
  StreamSec.DSI.IFC,
  StreamSec.DSI.CMS, StreamSec.DSI.PkixCert, StreamSec.DSI.PkixKeyManager,
  StreamSec.DSI.PkixCms, StreamSec.Mail.Message, StreamSec.Mail.SMIMEBroker;
function SigningBroker(aKeys: TstCertificateManager): TstSMIMEBroker;
var
  lSigned: TstMPSignedData;
begin
  Result := TstSMIMEBroker.Create(nil);
  try
    lSigned := TstMPSignedData.Create(Result);
    lSigned.ContentDigestAlg := haSHA256;
    Result.SignedFormat := ssfMultipartSigned;
    Result.AllowExpiredCertificates := False;
    Result.SignedData := lSigned;
    Result.KeysAndCerts := aKeys;
  except
    Result.Free;
    raise;
  end;
end;

Sign the outgoing message

Build a TsmEmail with its From address, recipients and body, then pass it to SignMailToFile with the signing manager and output filename. The broker wraps the content in a new message before saving it. Preserve those bytes when passing the .eml to storage or mail transport.

procedure SignMailToFile(aKeys: TstCertificateManager; aMessage: TsmEmail;
  const aFileName: string);
var
  lBroker: TstSMIMEBroker;
  lWrapped: TsmEmail;
begin
  lBroker := SigningBroker(aKeys);
  try
    lWrapped := TsmEmail.Create(lBroker);
    if not lBroker.Encode(MakeContentTypeArray([pSignedData]), aMessage, lWrapped) then
      raise Exception.Create('Could not sign the message');
    lWrapped.SaveToFile(aFileName);
  finally
    lBroker.Free;
  end;
end;

Verify the saved message

Pass the receiving manager, the expected sender certificate and the .eml path to ReadSignedMail. The broker decodes into a private message until the detached signature verifies, the expected certificate is reported by OnGoodSignature, and the decoded message has exactly one signed layer. Changing the signed text invalidates the signature.

type
  tExpectedMailSigner = class
    Expected: iCertificate;
    Seen: Boolean;
    procedure GoodSignature(Sender: TObject; aSignerCert: iCertificate);
  end;

procedure tExpectedMailSigner.GoodSignature(Sender: TObject; aSignerCert: iCertificate);
begin
  if Expected.SameCert(aSignerCert) then
    Seen := True;
end;

function ReadSignedMail(aKeys: TstCertificateManager; const aExpected: iCertificate;
  const aFileName: string): TsmEmail;
var
  lBroker: TstSMIMEBroker;
  lSigned: TstMPSignedData;
  lWrapped, lContent: TsmEmail;
  lSigner: tExpectedMailSigner;
  lActions: tContentTypeArray;
begin
  Result := nil;
  if not Assigned(aExpected) then Exit;
  if not aExpected.CheckValidity then Exit;
  lBroker := SigningBroker(aKeys);
  try
    lWrapped := TsmEmail.Create(lBroker);
    lWrapped.LoadFromFile(aFileName);
    if not TstSMIMEBroker.CheckIsMultipartSigned(lWrapped) then Exit;
    lSigner := tExpectedMailSigner.Create;
    try
      lSigner.Expected := aExpected;
      lSigned := TstMPSignedData(lBroker.SignedData);
      lSigned.OnGoodSignature := lSigner.GoodSignature;
      lContent := TsmEmail.Create(nil);
      try
        if not lBroker.Decode(lWrapped, lContent, lActions) then Exit;
        if not lSigned.DetachedSignature or not lSigner.Seen then Exit;
        if Length(lActions) <> 1 then Exit;
        if lActions[0] <> pSignedData then Exit;
        Result := lContent;
        lContent := nil;
      finally
        lContent.Free;
      end;
    finally
      lSigner.Free;
    end;
  finally
    lBroker.Free;
  end;
end;

A successful call returns a TsmEmail owned by the caller. Read its BodyText or attachments and free it in a finally block. A failed signature, an unexpected signer or plain mail returns nil. A file or parsing error can also raise an exception.

Encrypt and decrypt an S/MIME message shows how to protect the message content for its recipients. The mail notes cover MIME layers and canonical message bytes.

Reference

TstSMIMEBroker · TstMPSignedData · TstCertificateManager · TsmEmail · StreamSec.Mail.SMIMEBroker · StreamSec.Mail.Message · StreamSec.DSI.PkixCms · StreamSec.DSI.PkixKeyManager

Related tasks