var
Key: TTEAKey;
Salt: TSalt;
EncryptedText: RawByteString;
S: String;
SaltEncodedLen: Integer;
begin
// Create new (random) salt
Salt := InitSalt;
// Create new key from password
// Key will be different each time
// Because salt is different
Key := TEADeriveKey('password', @Salt);
// Encrypt some text with the above key
// (meaning "encrypt some text with the above password")
EncryptedText := TEAEncrypt(Key, 'clear text');
// Wipe key from memory - do this as soon as possible
TEADestroyKey(Key); // - same as SecureFree(Key);
// You must store salt with encrypted data
EncryptedText :=
RAWToString(@Salt, SizeOf(Salt)) +
EncryptedText;
// No longer needed, erase it
SecureFree(Salt);
// EncryptedText contains encrypted RAW bytes
// Do not output EncryptedText to any place which expects human-readable text
// Debug output
// Encrypted text is RAW bytes, so we need to convert it to something readable
// Encrypted value will always be different
Edit1.Text := HexEncodeString(EncryptedText);
// _____________________________________________
// Read stored salt
SaltEncodedLen := HexCalcEncodedSize(SizeOf(Salt)));
RAWFromString(Copy(EncryptedText, 1, SaltEncodedLen), @Salt);
// Remove salt from EncryptedText
EncryptedText := Copy(EncryptedText, SaltEncodedLen + 1, MaxInt);
// Create key from password
// Key will be the same as the one used for encryption above
Key := TEADeriveKey('password', @Salt);
// No longer needed, erase it
SecureFree(Salt);
// Decrypt text back
S := TEADecrypt(Key, EncryptedText);
// Wipe key from memory - do this as soon as possible
TEADestroyKey(Key); // - same as SecureFree(Key);
// Wipe also all data
SecureFree(EncryptedText);
// Now S = 'clear text'
// Call SecureFree for all data once you have finished working with it
SecureFree(S);
end;
|