#1 2024-08-24 13:08:29

anouri
Member
Registered: 2024-02-11
Posts: 43

Aes gcm 256

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

#2 2024-08-24 14:50:14

ab
Administrator
From: France
Registered: 2010-06-21
Posts: 14,548
Website

Re: Aes gcm 256

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.

Online

#3 2024-08-24 14:57:11

anouri
Member
Registered: 2024-02-11
Posts: 43

Re: Aes gcm 256

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

#4 2024-08-25 07:04:11

ab
Administrator
From: France
Registered: 2010-06-21
Posts: 14,548
Website

Re: Aes gcm 256

AES-GCM has an internal CTR: so you need to use TWO instances so that the CTR do match on both encrypt and decrypt side.

Online

#5 2024-08-25 11:03:07

anouri
Member
Registered: 2024-02-11
Posts: 43

Re: Aes gcm 256

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

Board footer

Powered by FluxBB