unit Tools.Crypt;
interface
uses
System.SysUtils,
DECUtil, DECHash,
DECHashBase, DECCipherBase, DECCiphers, DECFormatBase, DECFormat,
DECHashAuthentication, DECRandom;
const
conKey = '
aYr14iaz8u)xO7Ok';
var
CipherMode: TCipherMode = cmCBCx;
HashClass: TDECHashClass = THash_SHA256;
TextFormat: TDECFormatClass = TFormat_Base64;
KDFIndex: LongWord = 1;
type
TToolsCrypt =
class
public
class function Decrypt(aHash:
string; aKey:
string = '
'):
string;
class function Encrypt(aText:
string; aKey:
string = '
'):
string;
end;
implementation
{ TToolsCrypt }
class function TToolsCrypt.Decrypt(aHash, aKey:
string):
string;
var
Cipher: TCipher_Rijndael;
Salt: RawByteString;
//Binary;
Data: RawByteString;
Check: RawByteString;
Pass: RawByteString;
PassBytes: TBytes;
Len: Integer;
begin
if aKey = '
'
then
begin
aKey := conKey;
end;
Cipher := TCipher_Rijndael.Create;
try
Salt := ValidFormat(TextFormat).Decode(RawByteString(aHash));
Len := Length(Salt) - 16 - Cipher.Context.BufferSize;
Data := Copy(Salt, 17, Len);
Check := Copy(Salt, Len + 17, Cipher.Context.BufferSize);
SetLength(Salt, 16);
PassBytes := THash_SHA256.KDFx(aKey[1],
Length(aKey) * 2,
Salt[1],
Length(Salt),
Cipher.Context.KeySize,
KDFIndex);
SetLength(Pass, Length(PassBytes));
Move(PassBytes[0], Pass[low(Pass)], Length(PassBytes));
Cipher.Mode := CipherMode;
Cipher.Init(Pass);
SetLength(Result, Len
div 2);
Cipher.Decode(Data[1], Result[1], Len);
if Check <> Cipher.CalcMAC
then
begin
Result := '
';
end;
finally
Cipher.Free;
//ProtectBinary(Salt);
ProtectString(Salt);
ProtectString(Data);
ProtectString(Check);
ProtectString(Pass);
end;
end;
class function TToolsCrypt.Encrypt(aText, aKey:
string):
string;
var
Cipher: TCipher_Rijndael;
SaltBytes : TBytes;
Salt: RawByteString;
//Binary;
Data: RawByteString;
//Binary;
Pass: RawByteString;
//Binary;
PassBytes: TBytes;
begin
if aKey = '
'
then
begin
aKey := conKey;
end;
Cipher := TCipher_Rijndael.Create;
try
SaltBytes := RandomBytes(16);
//RandomBinary(16);
SetLength(Salt, Length(SaltBytes));
Move(SaltBytes[0], Salt[low(Salt)], Length(SaltBytes));
PassBytes := THash_SHA256.KDFx(aKey[1],
Length(aKey) * 2,
Salt[1],
Length(Salt),
Cipher.Context.KeySize,
KDFIndex);
SetLength(Pass, Length(PassBytes));
Move(PassBytes[0], Pass[low(Pass)], Length(PassBytes));
Cipher.Mode := CipherMode;
Cipher.Init(Pass);
SetLength(Data, Length(aText) * 2);
Cipher.Encode(aText[1], Data[1], Length(Data));
Result :=
string(ValidFormat(TextFormat).Encode(Salt + Data + Cipher.CalcMAC));
finally
Cipher.Free;
ProtectString(Salt);
ProtectString(Data);
ProtectString(Pass);
end;
end;
end.