You are not logged in.
Pages: 1
After 2 days I couldn't get this code to work properly:
error = Unexpected TAesGcm.Decrypt
var
AES: TAesGcm;
Key: AnsiString;
PlainText: string;
CipherText: RawUtf8;
akey : RawByteString;
s: RawByteString;
begin
//Key := GenerateRandomString(32);
Key := '12345678901234567890123456789012';
akey := HexToBin(SHA256(Key));
PlainText := '123';
s := StringToUTF8(PlainText);
AES := TAesGcm.Create(akey, 256);
CipherText := BinToBase64(AES.EncryptPkcs7(s, True));
s := StringToUTF8(CipherText);
PlainText := AES.DecryptPkcs7(Base64ToBin(s), True);
ShowMessage(UTF8ToString(PlainText));
Last edited by anouri (2024-08-24 13:08:44)
Offline
TAesGcm.Create(akey, 256); is wrong - you are sending the pointer of the akey string, not the string content.
It is clearly documented:
// - warning: aKey is an untyped constant, i.e. expects a raw set of memory
// bytes: do NOT use assign it with a string or a TBytes instance: you would
// use the pointer to the data as key - either digest the string via
// CreateFromPbkdf2 or use Create(TBytes)
constructor Create(const aKey; aKeySizeBits: cardinal); reintroduce; overload; virtual;
You need to write TAesGcm.Create(pointer(akey)^, 256);
And you better need to create a new TAesGcm instance for decryption.
Since you seem to be lost with the details, you better use high-level ICryptCipher and Encrypt() and Decrypt() factories from mormot.crypt.secure.
Offline
After making the suggested change, the same error occurred again. But by creating a new instance, the problem was solved!
Thanks. you are the best!
Offline
Actually, I was in the learning and testing phase. In actual programming, I created a function for encrypt and another for decrypt.
Thank you again for the valuable and great work you are doing
Offline
Pages: 1