var
ACipherClass: TDECCipherClass = TCipher_Blowfish;
ACipherMode: TCipherMode = cmCFS8;
AHashClass: TDECHashClass = THash_SHA1;
ATextFormat: TDECFormatClass = TFormat_MIME64;
AKDFIndex: LongWord = 1;
function Encrypt(
const AText:
String;
const APassword:
String):
String;
var
ASalt: Binary;
AData: Binary;
APass: Binary;
begin
with ValidCipher(ACipherClass).Create, Context
do
try
ASalt := RandomBinary(16);
APass := ValidHash(AHashClass).KDFx(APassword, ASalt, KeySize, TFormat_Copy, AKDFIndex);
Mode := ACipherMode;
Init(APass);
AData := ASalt + EncodeBinary(AText) + CalcMAC;
Result := ValidFormat(ATextFormat).Encode(AData);
finally
Free;
ProtectBinary(ASalt);
ProtectBinary(AData);
ProtectBinary(APass);
end;
end;
function Decrypt(
const AText:
String;
const APassword:
String):
String;
var
ASalt: Binary;
AData: Binary;
ACheck: Binary;
APass: Binary;
ALen: Integer;
begin
with ValidCipher(ACipherClass).Create, Context
do
try
ASalt := ValidFormat(ATextFormat).Decode(AText);
ALen := Length(ASalt) -16 -BufferSize;
AData := System.Copy(ASalt, 17, ALen);
ACheck := System.Copy(ASalt, ALen +17, BufferSize);
SetLength(ASalt, 16);
APass := ValidHash(AHashClass).KDFx(APassword, ASalt, KeySize, TFormat_Copy, AKDFIndex);
Mode := ACipherMode;
Init(APass);
Result := DecodeBinary(AData);
if ACheck <> CalcMAC
then
raise Exception.Create('
Invalid data');
finally
Free;
ProtectBinary(ASalt);
ProtectBinary(AData);
ProtectBinary(ACheck);
ProtectBinary(APass);
end;
end;