A
A
Anton2014-05-17 15:40:50
Delphi
Anton, 2014-05-17 15:40:50

Different results of AES encryption

I am writing a program that encrypts text with AES. There are three Memo components with text (open, encrypted, decrypted) on the form. I don’t know if this is a problem or not, but the first few encryptions result in a different ciphertext. After 5-10 times, it takes the same form on all iterations.
Here's what the ciphertext memo outputs.

Ї?HЏ=РУ9јЪoBЅхАP
т”#u„ЁЩќ¶ё¤aB 
eжјф!лSAEѓR‰¬р
іѓnЄу/§юа:6oR%X
іѓnЄу/§юа:6oR%X
Sжыувчђ5n)Гњ‡rШ
іѓnЄу/§юа:6oR%X
іѓnЄу/§юа:6oR%X
іѓnЄу/§юа:6oR%X

And here is the actual button code that performs all these operations.
//Ñ÷èòûâàåì äëèíó êëþ÷à è óêàçûâàåì Nk è Nr
case ListBox1.ItemIndex of
  0:begin Nk:=4;Nr:=10; end;
  1:begin Nk:=6;Nr:=12; end;
  2:begin Nk:=8;Nr:=14; end;
  end;

//Ñ÷èòûâàåì êëþ÷
s:=KText.Text;
for i:=1 to Nk*4 do
  key[i]:=Ord(s[i]);

//Ðàñøèðåíèå êëþ÷à
keys:=KeyExpansion(key,Nk);

//Èíèöèàëèçàöèÿ âõîäà
s:=MText.Lines[0];
for i:=1 to 16 do open[i]:=Ord(s[i]);

//Øèôðîâàíèå
close:=Cipher(open,keys,Nr);

s:='';for i:=1 to 16 do s:=s+Char(close[i]);
CText.Lines.Add(s);

//Ðàñøèôðîâàíèå
case ListBox2.ItemIndex of
  0:decrypted:=InvCipher(close,keys,Nr);
  1:decrypted:=EqInvCipher(close,keys,Nr);
  end;

s:='';for i:=1 to 16 do s:=s+Char(decrypted[i]);
PText.Lines.Add(s);

ps no random values ​​or functions are used in the KeyExpansion and Cipher functions.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
M_PRO, 2014-11-25
@M_PRO

Obviously this is a problem. This behavior should not be.
Most likely in some of the functions you are using an uninitialized variable.
Judging by your description, the text is deciphered correctly. So the point is in the KeyExpansion function or the initialization of the key array. Try putting in something like

for Index := Low(Key) to Hi(Key) do
    Key[Index] := 0;

before lines
for i:=1 to Nk*4 do
  key[i]:=Ord(s[i]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question