Password Based Encrypt/Decrypt

This example demonstrates how to use the various symmetric encrypt/decrypt functions with a password based key.

Example code encrypt:


procedure TFrmMain.btnEncryptPWClick(Sender: TObject);
var
  Key: IRwBCryptKey;
  Alg: TRwCryptCipherAlgorithm;
begin
  // Get the chosen algorithm
  Alg := TRwCryptCipherAlgorithm(cmbBxAlgorithm.Items.Objects[cmbBxAlgorithm.ItemIndex]);

  // Create an encryption key based on the password and the algorithm
  // Note: Use UTF8 Password = False and calgSHA1 to derive keys compatible with Easy Crypt CSP
  Key := TRwBCryptCipherProvider.Cipher(Alg).DeriveKey_CSP(edtPassword.Text, True, calgSHA256);

  // It is also possible to set the keyvalue directly
  // using the ImportKey

  // Encrypt the text to encrypt
  // Base64 encode the encrypted data and put it in the edit
  // Note: Base64 encoded strings are AnsiStrings
  edtEncryptedPW.Text := Key.EncryptString(edtToEncryptPW.Text, True, []).Encode(beBase64);
end;

Example code decrypt:


procedure TFrmMain.btnDecryptPWClick(Sender: TObject);
var
  Key: IRwBCryptKey;
  Alg: TRwCryptCipherAlgorithm;
begin
  // Get the chosen algorithm
  Alg := TRwCryptCipherAlgorithm(cmbBxAlgorithm.Items.Objects[cmbBxAlgorithm.ItemIndex]);

  // Create an encryption key based on the password and the algorithm
  // Note: Use UTF8 Password = False and calgSHA1 to derive keys compatible with Easy Crypt CSP
  Key := TRwBCryptCipherProvider.Cipher(Alg).DeriveKey_CSP(edtPassword.Text, True, calgSHA256);

  // It is also possible to set the keyvalue directly
  // using the ImportKey

  // Decrypt
  // Note: Base64 encoded strings are AnsiStrings
  edtDecryptedPW.Text := Key.DecryptString(edtEncryptedPW.Text, beBase64, True, []);
end;


Back to Examples