Contents · Forum Home · StreamSec Tools 4.1.5.365 documentation

Encrypt and decrypt an S/MIME message

Protect a MIME body and its attachments for recipients whose encryption certificates you already trust. The sender needs their public certificates. Each recipient opens the resulting .eml with their own private key.

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.

Make recipient certificates available

Use an enabled TstCertificateManager with a subject-name index (tKeyIndexSubjectClearTextName) configured with avEmailAddress alone. The broker looks up each mailbox as /E=address. For this lookup, use a certificate with the address in its subject, an RSA encryption public key and keyEncipherment usage. If an extended key usage is present, it must permit emailProtection. Provision current certificates that your application has validated for each mailbox.

The broker includes From, a distinct Sender, and the To, Cc and Bcc addresses. This lets the sender read a sent copy. Each recipient entry can identify its certificate, including one for a Bcc recipient. The outer address fields and Subject are outside the encrypted content.

uses
  System.SysUtils, System.Classes, stSecUtils, stOIDs, stPkixExtension,
  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;
type
  tEncryptionBroker = class(TstSMIMEBroker)
    procedure CheckRecipients(aMessage: TsmEmail);
    procedure MissingRecipient(Sender: TObject; aAddress: string);
  end;

procedure tEncryptionBroker.MissingRecipient(Sender: TObject; aAddress: string);
begin
  raise Exception.CreateFmt('No encryption certificate for %s', [aAddress]);
end;

procedure tEncryptionBroker.CheckRecipients(aMessage: TsmEmail);
var
  lAddresses: TStringList;
  lAddress, lFrom, lSender: string;
  lCert: iCertificate;
begin
  lAddresses := TStringList.Create;
  try
    aMessage.GetEnvelopeAddresses(lAddresses, True);
    if lAddresses.Count = 0 then
      raise Exception.Create('The message has no recipients');
    lFrom := aMessage.FromAddress;
    if lFrom <> '' then lAddresses.Add(lFrom);
    lSender := aMessage.SenderAddress;
    if (lSender <> '') and not SameText(lSender, lFrom) then
      lAddresses.Add(lSender);
    for lAddress in lAddresses do begin
      lCert := nil;
      lCert := GetCertByEMail(lAddress, rsaEncryption, [keyEncipherment], False);
      if not Assigned(lCert) then MissingRecipient(Self, lAddress);
      if not SameText(lCert.tbsCertificate.subject.AsRdnSequence.EmailAddress,
        lAddress) then
        MissingRecipient(Self, lAddress);
      if not lCert.CheckValidity then
        raise Exception.CreateFmt('Certificate outside its validity period for %s',
          [lAddress]);
    end;
  finally
    lAddresses.Free;
  end;
end;

function EncryptionBroker(aKeys: TstCertificateManager): tEncryptionBroker;
var
  lEnvelope: TstMPEnvelopedData;
begin
  Result := tEncryptionBroker.Create(nil);
  try
    lEnvelope := TstMPEnvelopedData.Create(Result);
    Result.AllowExpiredCertificates := False;
    Result.EnvelopedData := lEnvelope;
    Result.KeysAndCerts := aKeys;
    with lEnvelope.SMIMECapabilities.Add as tSMIMECapabilityItem do begin
      CipherAlg := caRijndael;
      CipherMode := cmCBC;
      KeyLength := 32;
    end;
    lEnvelope.UseRSAOAEPEncryption := True;
    lEnvelope.RSAOAEPHashAlgorithm := haSHA256;
    lEnvelope.RSAOAEPMGFHashAlgorithm := haSHA256;
    lEnvelope.OnRecipientCertNotFound := Result.MissingRecipient;
  except
    Result.Free;
    raise;
  end;
end;

The sample checks the certificate address and validity for every mailbox before encoding and also handles a missing certificate during encryption. It selects AES-256-CBC for the content and RSA-OAEP with SHA-256 for key transport. Recipients need support for both choices. Encryption alone establishes no sender identity.

Encrypt and save

Pass a populated TsmEmail, the sender's certificate manager and an output filename to EncryptMailToFile. It saves the wrapped message only after all intended addresses have been resolved and encryption succeeds.

procedure EncryptMailToFile(aKeys: TstCertificateManager; aMessage: TsmEmail;
  const aFileName: string);
var
  lBroker: tEncryptionBroker;
  lWrapped: TsmEmail;
begin
  lBroker := EncryptionBroker(aKeys);
  try
    lWrapped := TsmEmail.Create(lBroker);
    lBroker.CheckRecipients(aMessage);
    if not lBroker.Encode(MakeContentTypeArray([pEnvelopedData]),
      aMessage, lWrapped) then
      raise Exception.Create('Could not encrypt the message');
    lWrapped.SaveToFile(aFileName);
  finally
    lBroker.Free;
  end;
end;

Open the encrypted message

Pass the recipient's manager and the .eml path to ReadEncryptedMail. The manager needs the recipient certificate and matching private key. Configure its public-key and CMS issuer/serial indexes so the worker can resolve the recipient identifier in the envelope.

function ReadEncryptedMail(aKeys: TstCertificateManager;
  const aFileName: string): TsmEmail;
var
  lBroker: tEncryptionBroker;
  lWrapped, lContent: TsmEmail;
  lActions: tContentTypeArray;
begin
  Result := nil;
  lBroker := EncryptionBroker(aKeys);
  try
    lWrapped := TsmEmail.Create(lBroker);
    lWrapped.LoadFromFile(aFileName);
    lContent := TsmEmail.Create(nil);
    try
      if not lBroker.Decode(lWrapped, lContent, lActions) then Exit;
      if Length(lActions) <> 1 then Exit;
      if lActions[0] <> pEnvelopedData then Exit;
      Result := lContent;
      lContent := nil;
    finally
      lContent.Free;
    end;
  finally
    lBroker.Free;
  end;
end;

The result is a new message owned by the caller. Read its MIME content and free it in a finally block. A message without the expected encryption layer, or an envelope for which no key is found, returns nil. File, parsing and cryptographic errors can also raise exceptions.

Sign and verify an S/MIME message covers sender authentication. The mail notes describe how signing and encryption layers are ordered.

Reference

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

Related tasks