Contents · Forum Home · StreamSec Tools 4.1.5.365 documentation

Encrypt a file for a recipient with CMS

Use the recipient's public certificate to create a CMS envelope. The recipient opens the envelope with the corresponding private key. This example uses RSA-OAEP to wrap the content key and AES-256-GCM to protect the file contents.

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.

Choose the recipient and encrypt

Obtain the recipient's RSA certificate through a trusted channel. Check its identity, validity and permitted key usage for key encipherment. Check a certificate chain and its revocation covers the chain and revocation checks.

uses
  System.Classes, System.SysUtils, stSecUtils, stReadStrm,
  stSHA256, stDrbgAesCtr, stAESCT, stAESNI,
  StreamSec.DSI.Arith, StreamSec.DSI.IFC, StreamSec.DSI.PkixCert,
  StreamSec.DSI.PkixKeyManager, StreamSec.DSI.CMS, StreamSec.DSI.PkixCms;
function EncryptFileForRecipient(aKeys: TstCertificateManager; const aRecipient: iCertificate;
  const aFileName, aEnvelopeFile: string): Boolean;
var
  lCMS: TstMPEnvelopedData;
  lInput: TFileStream;
  lEnvelope: TMemoryStream;
begin
  Result := False;
  if (aKeys = nil) or (aRecipient = nil) then Exit;
  lCMS := TstMPEnvelopedData.Create(nil);
  try
    lCMS.KeysAndCerts := aKeys;
    with lCMS.SMIMECapabilities.Add as tSMIMECapabilityItem do begin
      CipherAlg := caRijndael;
      CipherMode := cmGCM;
      KeyLength := 32;
    end;
    lCMS.UseRSAOAEPEncryption := True;
    lCMS.RSAOAEPHashAlgorithm := haSHA256;
    lCMS.RSAOAEPMGFHashAlgorithm := haSHA256;
    lInput := TFileStream.Create(aFileName, fmOpenRead or fmShareDenyWrite);
    try
      lEnvelope := TMemoryStream.Create;
      try
        Result := lCMS.Encrypt(aRecipient, lInput, lEnvelope) and
                  (lCMS.EnvelopeType = pAuthEnvelopedData);
        if Result then lEnvelope.SaveToFile(aEnvelopeFile);
      finally
        lEnvelope.Free;
      end;
    finally
      lInput.Free;
    end;
  finally
    lCMS.Free;
  end;
end;

Pass an enabled TstCertificateManager, the recipient certificate, the input file and a separate envelope path, for example report.pdf.p7m. Encryption needs the recipient's public key. KeyLength is in bytes. Selecting GCM produces CMS AuthEnvelopedData; the two hash properties select SHA-256 for OAEP and its MGF1 mask.

Open the envelope

Configure the recipient's certificate manager with the certificate, its matching private key, a public-key index and a CMS issuer-and-serial index (tKeyIndexSerialIssuerCMS). These let the component find the recipient named in the envelope and the private key belonging to it.

function DecryptFileForRecipient(aKeys: TstCertificateManager;
  const aEnvelopeFile, aOutputFile: string): Boolean;
var
  lCMS: TstMPEnvelopedData;
  lInput: TFileStream;
  lPlain: tSecureMemoryStream;
begin
  Result := False;
  if aKeys = nil then Exit;
  lCMS := TstMPEnvelopedData.Create(nil);
  try
    lCMS.KeysAndCerts := aKeys;
    lInput := TFileStream.Create(aEnvelopeFile, fmOpenRead or fmShareDenyWrite);
    try
      lPlain := tSecureMemoryStream.Create;
      try
        Result := lCMS.Decrypt(lInput, lPlain) and
                  (lCMS.EnvelopeType = pAuthEnvelopedData);
        if Result then lPlain.SaveToFile(aOutputFile);
      finally
        lPlain.Free;
      end;
    finally
      lInput.Free;
    end;
  finally
    lCMS.Free;
  end;
end;

Use a separate output path. The function saves the recovered bytes only after decryption succeeds and the component reports an authenticated envelope. A missing recipient key or an invalid GCM tag gives False. File I/O and malformed input can raise exceptions. The sample holds the recovered content in memory until its authentication completes, so allow space for the full file.

Anyone with the recipient's public certificate can create an envelope. For proof of who signed the content, see Sign a file and verify its detached CMS signature. The PKIX notes list the supported CMS recipient types.

Reference

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

Related tasks