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

Generate RSA Key and Sign a String

See more RSA Examples

Demonstrates how to generate a new RSA public/private key pair and use it to generate a signature for a string. The (binary) digital signature is returned as a hexidecimalized string.

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.PrivateKey,
  Chilkat.Rsa,
  Chilkat.PublicKey;

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

procedure RunDemo;
var
  success: Boolean;
  rsa: TRsa;
  privKey: TPrivateKey;
  strData: string;
  hexSig: string;
  pubKey: TPublicKey;

begin
  success := False;

  //  This example assumes the Chilkat API to have been previously unlocked.
  //  See Global Unlock Sample for sample code.

  rsa := TRsa.Create;

  //  Generate a 2048-bit RSA key.
  privKey := TPrivateKey.Create;
  success := rsa.GenKey(2048,privKey);

  rsa.UsePrivateKey(privKey);

  //  Return the signature in hex.
  rsa.EncodingMode := 'hex';

  strData := 'This is the string to be signed.';

  //  Sign the SHA256 hash of the string.
  hexSig := rsa.SignStringENC(strData,'sha256');

  WriteLn(hexSig);

  //  Now verify the signature:
  pubKey := TPublicKey.Create;
  privKey.ToPublicKey(pubKey);
  rsa.UsePublicKey(pubKey);

  success := rsa.VerifyStringENC(strData,'sha256',hexSig);
  if (success = True) then
    begin
      WriteLn('Signature verified!');
    end
  else
    begin
      WriteLn(rsa.LastErrorText);
    end;

  //  Try it with an invalid signature:
  success := rsa.VerifyStringENC(strData,'sha256','not a valid sig');
  if (success = True) then
    begin
      WriteLn('Signature verified!');
    end
  else
    begin
      WriteLn('Signature validation failed!');
    end;

  //  Try it with invalid data:
  success := rsa.VerifyStringENC('Not the original data','sha256',hexSig);
  if (success = True) then
    begin
      WriteLn('Signature verified!');
    end
  else
    begin
      WriteLn('Signature validation failed!');
    end;


  rsa.Free;
  privKey.Free;
  pubKey.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.