The key is expected to be of the specified size, not less. There is no way of Create() to know how much data is really in aKey: it is just a pointer.
If you need some key padding, do it before calling.
So your code is to be fixed.
in:
constructor TAESAbstract.Create(const aKey; aKeySize: cardinal);
begin
if (aKeySize<>128) and (aKeySize<>192) and (aKeySize<>256) then
raise ESynCrypto.CreateUTF8('%.Create(aKeySize=%): 128/192/256 required',[self,aKeySize]);
fKeySize := aKeySize;
fKeySizeBytes := fKeySize shr 3;
MoveFast(aKey,fKey,fKeySizeBytes); <<<--- (1)
end;
(1) if the key is, for example, "12345678" the byte array TAESKey should be:
[49, 50, 51, 52, 53, 54, 55, 56, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
in other words, the rest of array should be completed with zeroes but is filled with other values that are valids. For workaround I added Key as property in TAESAbstract with read/write and after create I refilling with correct data and it works.
Can you tell me if this behavior is by design or bug ?
UPDATE:
I removed Key property from TAESAbstract and implemented TAESAbstrackHack for accessing fKey protected member.
I don't know how patch MoveFast for non-filling with invalid values the rest of byte array. I think that Create constructor should have extra parameter with length of key text.
Thanks.
]]>Thanks again.
]]>For instance, at first glance, the DotNetFiddle version is padding the key UTF-8 with zeros up to the key size of 256 bits, whereas you are calling TAESCBC.Create(const aKey; aKeySize: cardinal) which is pretty much incorrect because you are hashing the lKey pointer on stack, not the bytes themselves.
Padding UTF-8 with zeros is weak for sure. I wouldn't use this C# code as reference.
Use a proven password hashing method like TAESCBC.CreateFromPBKDF2() using PBKDF2_HMAC_SHA256.
Any idea why mORMot encryption not working ?
Thanks.
]]>var
lKey: TBytes;
lIV: TAESBlock;
lText, lTextEncrypted, lIVText: RawByteString;
lAESCBC: TAESCBC;
begin
...
// edtKey.Text is KEY
// edtSource.Text is TEXT TO ENCRYPT
SetLength(lKey, Length(edtKey.Text));
SynCommons.HexToBin(Pointer(edtKey.Text), @lKey, Min(Length(edtKey.Text),SizeOf(lKey)));
RawByteStringToBytes(RawByteString(edtKey.Text), lKey);
lAESCBC := TAESCBC.Create(lKey, CRYPT_KEY_SIZES[2]{=256});
try
lText := StringToUTF8(edtSource.Text);
TAESPRNG.Main.FillRandom(lIV);
lAESCBC.IV := lIV;
lTextEncrypted := SynCommons.BinToBase64(lAESCBC.EncryptPKCS7(lText));
lIVText := SynCommons.BinToBase64(@lAESCBC.IV, SizeOf(lAESCBC.IV));
edtDest.Text := UTF8ToString(lTextEncrypted)+'.'+lIVText;
finally
lAESCBC.Free;
end;
...
end;
and the key generated with the above code
KEY=key
TEXT TO ENCRYPT=text to encrypt
oTfXA3+lm6aiOaGYjCsk+Q==.OX0qIq1iSEMhTdw/fl0ehg== (the dot is a separator)
raise an exception <b>Padding is invalid and cannot be removed.</b>
For testing I'm using dotfiddle.net in https://dotnetfiddle.net/tlO25C
What's wrong ?
Thanks.
]]>