Incorrect results when using the TTripleDES class

Issue #377 invalid
MasterpieceDeveloper created an issue

Hello
Maybe I'm not using your class correctly.
I get these results:

var LCrypt: ISymmetricAlgorithm := TTripleDES.Create;

LCrypt.Key := TBuffer.Create(16);

LCrypt.CipherMode := TCipherMode.ECB;

var LSecret := LCrypt.Encrypt('123').ToHexString; // '0152E62F0F7C8673'

var LValue := PChar(LCrypt.Decrypt(TBuffer.FromHexString(LSecret))); // '123Ȃ', not '123'

Comments (2)

  1. Stefan Glienke repo owner

    You are indeed not using it correctly because you are assuming that you can hardcast TBuffer to PChar. This is the defect because it only contains the data and not a zero terminator. That means your PChar is causing a buffer overflow and reading into invalid memory - due to overallocating of the memory manager that might still be allocated memory which eventually contains a zero.

    The correct way would be to use TEncoding to get back the unicode string from the bytes:

      var LValue := LCrypt.Decrypt(TBuffer.FromHexString(LSecret));
      Writeln(TEncoding.Unicode.GetString(LValue.ToBytes));
    
  2. Log in to comment