Sample code for 30+ languages & platforms
Pascal (Lazarus/Delphi)

Decrypt S/MIME using Added Credential Sources

See more MIME Examples

Loads a CMS/PKCS #7 encrypted S/MIME message and decrypts it back to the original MIME content.

The recipient's certificate and private key are supplied from a PFX added with AddPfxSourceFile, and Decrypt automatically selects the matching private key based on the CMS recipient information.

The file paths are relative to the application's current working directory. Absolute paths may also be used. Supply the paths appropriate to your own environment.

Background. Decrypt requires access to the recipient's private key. Chilkat matches the encrypted message's recipient identifiers against the certificates and keys made available through sources such as AddPfxSourceFile, AddDecryptCert, or a certificate vault.

Chilkat Pascal (Lazarus/Delphi) Downloads

Pascal (Lazarus/Delphi)
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.Mime;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  success: Boolean;
  mime: TMime;
  pfxPassword: string;
  body: string;

begin
  success := False;

  mime := TMime.Create;
  success := mime.LoadMimeFile('qa_data/encrypted.eml');
  if (success = False) then
    begin
      WriteLn(mime.LastErrorText);
      Exit;
    end;

  //  Load the recipient's certificate and private key (from a PFX) so decryption can find them.  The
  //  PFX password should come from a secure source rather than being hard-coded.
  pfxPassword := 'myPfxPassword';
  success := mime.AddPfxSourceFile('qa_data/recipient.pfx',pfxPassword);
  if (success = False) then
    begin
      WriteLn(mime.LastErrorText);
      Exit;
    end;

  //  Decrypt.  Chilkat identifies the correct recipient from the CMS recipient info and uses the
  //  matching private key from the added sources.
  success := mime.Decrypt();
  if (success = False) then
    begin
      WriteLn(mime.LastErrorText);
      Exit;
    end;

  body := mime.GetBodyDecoded();
  if (mime.LastMethodSuccess = False) then
    begin
      WriteLn(mime.LastErrorText);
      Exit;
    end;
  WriteLn(body);


  mime.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.