To adapt your existing Delphi code using DEC (Delphi Encryption Compendium) version 3 to the latest version available on GitHub, you will need to modify the cipher creation, key derivation, and encoding processes slightly. The core logic and compatibility with existing decryption should remain the same.
Here's the adjusted version using the newest Delphi Encryption Compendium:
uses
DECUtil, DECCipherModes, DECCipher, DECFormat, DECData, DECHash;
function Encrypt(const APassword: string; const AText: string): string; overload;
var
ASalt: TBytes;
AData: TBytes;
APass: TBytes;
Cipher: TDECipher;
Format: TDECFormat;
MAC: TBytes;
begin
Cipher := TDECRijndael.Create;
Format := TFormat_MIME64.Create;
try
// Generate Salt
ASalt := GenerateRandomBytes(16);
// Derive Key
APass := TDECHashWhirlpool.KDFx(AnsiBytesOf(APassword), ASalt, 32, 1);
// Initialize Cipher
Cipher.Init(APass, nil);
Cipher.Mode := cmCBCx;
// Encrypt Data
SetLength(AData, Length(AText) * SizeOf(Char));
Cipher.Encode(AnsiBytesOf(AText), AData);
// Calculate MAC
SetLength(MAC, Cipher.MACSize);
Cipher.CalcMAC(MAC);
// Combine Salt, Data, and MAC
Result := Format.Encode(ASalt + AData + MAC);
finally
Cipher.Free;
Format.Free;
SecureClear(ASalt);
SecureClear(AData);
SecureClear(APass);
end;
end;
Key Changes:
-
DECPrefixTypes:
- Use
TBytes instead of Binary which is more common in recent Delphi versions.
-
Random Bytes Generation:
- Use
GenerateRandomBytes instead of RandomBinary.
-
Encoding and Key Handling:
- Replace the direct use of
TFormat_Mime64.Encode with a more object-oriented approach by creating a TFormat_MIME64 object.
-
KDFx Function:
- The password derivation and hashing need to be adapted to
AnsiBytesOf, ensuring compatibility between versions specifically for strings.
-
Secure Clear:
- Use
SecureClear for clearing sensitive information from memory.
Make sure to replace AnsiBytesOf and SizeOf(Char) with appropriate functions or constants as per your Delphi version or custom utility functions, since these can vary depending on your environment or requirements.
Compatibility:
Ensure to test the output against existing decryption mechanisms to maintain compatibility. Adjust any minor details which might be version-specific, especially regarding MAC and padding bytes, to reflect those changes as per your specific requirements or existing encryption logic.