Pascal (Lazarus/Delphi)
Pascal (Lazarus/Delphi)
Encrypt MIME for a Recipient Certificate
See more MIME Examples
Demonstrates encrypting the current MIME entity for a single recipient using the Mime.Encrypt method. The entity is replaced with CMS/PKCS #7 encrypted S/MIME that only the holder of the recipient's private key can read.
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. S/MIME encryption uses the recipient's public certificate to protect a message so that only the matching private key can recover it. The recipient certificate must be RSA-based. Only the recipient's public key is needed to encrypt—the private key is required to decrypt.
Chilkat Pascal (Lazarus/Delphi) Downloads
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.Cert,
Chilkat.Mime;
// ---------------------------------------------------------------------------
procedure RunDemo;
var
success: Boolean;
mime: TMime;
cert: TCert;
begin
success := False;
mime := TMime.Create;
success := mime.SetBodyFromPlainText('This message will be encrypted.');
if (success = False) then
begin
WriteLn(mime.LastErrorText);
Exit;
end;
// Load the recipient's certificate (public key only is sufficient for encrypting).
cert := TCert.Create;
success := cert.LoadFromFile('qa_data/recipient.cer');
if (success = False) then
begin
WriteLn(cert.LastErrorText);
Exit;
end;
// Encrypt for the recipient. The entity is replaced with CMS/PKCS #7 encrypted S/MIME that only
// the holder of the recipient's private key can decrypt. The certificate must be RSA-based.
success := mime.Encrypt(cert);
if (success = False) then
begin
WriteLn(mime.LastErrorText);
Exit;
end;
success := mime.SaveMime('qa_output/encrypted.eml');
if (success = False) then
begin
WriteLn(mime.LastErrorText);
Exit;
end;
WriteLn('Message encrypted.');
mime.Free;
cert.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.