TurboPack / LockBox

LockBox is a Delphi and C++Builder library for cryptography.
106 stars 38 forks source link

DES Encrypt Using UNICODE encoding #15

Closed SilentException closed 3 years ago

SilentException commented 4 years ago

Hi,

in old(er) versions there were couple of string methods available, like GenerateKeyW and EncryptStringW. In newer versions we have option to use the same by setting Encoding property. But, it is broken for UNICODE, because stream that contains Base64 bytes is returning pure ANSI bytes and the TlbDES (example I am using) is doing GetString() on the result which expects the result to be encoded in the way Encoding was set.

Consider this, using old versions (please excuse missing try..finally, it is just an example)

DES := TLbDES.Create(nil);
DES.GenerateKey**W**('TEST');
Result := DES.EncryptString**W**('TEST_STRING');

Result is 8NxSs3eF6IqVqpOtwPGlYrNY1Nu30bt9.

Move on to the new versions we have this:

DES := TLbDES.Create(nil);
DES.Encoding := TEncoding.UNICODE;
DES.GenerateKey('TEST');
Result := DES.EncryptString('TEST_STRING');

And the Result is jibberish - 丸卸㍳䙥䤶噱灱瑏偷汇牙奎丱㍵戰㥴. This clearly looks like encoding error so looking at the stuff happening in background, result from DESEncryptBytesEx() has correct bytes internally, only not in the UNICODE format the GetString() in TLbDES.EncryptString expects them to be in. So the GetString is returning garbage.

Fix is not too hard to do but I imagine your implementation would differ from mine since you know the whole library better than I do currently :)

SilentException commented 4 years ago

Also, same goes for decryption.. DESEncryptBytesEx(InBytes, Key, false) has InBytes coded from UNICODE string. Call to LbDecodeBase64 fails because of all the zeroes inbetween character bytes.

romankassebaum commented 3 years ago

Fixed.