1

I have next code:

FileStream fs = new FileStream("test.crp",FileMode.Create);
Aes aes = Aes.Create();
FileStream fsKeys = new FileStream("keys.key",FileMode.Open);
fsKeys.Read(aes.IV,0,16);
fsKeys.Read(aes.Key,0,32);
fsKeys.Close();

And the problem is that: aes.IV and aes.Key are not changed during the Read operation from file.

And I can only assign a new value to them using the assignment operators:

 byte [] iv = new byte[16];
 byte [] key = new byte[32];
 aes.IV = iv;
 aes.Key = key;

Is it a right behavior? If so, Then to what memory block do I read, when I use fs.Read?

1 Answers1

1

That is because Aes.IV and Aes.Key are returning "cloned" byte array of its member variables.

By fsKeys.Read(aes.IV,0,16);, you are modifying the cloned IV array, not the member variable behind aes.IV.

You can check the source code here: https://referencesource.microsoft.com/#mscorlib/system/security/cryptography/symmetricalgorithm.cs,97c6f2476150a40d

Mike Mat
  • 632
  • 7
  • 15
  • Thank You! But why do they clone it? – Rassul Yunussov Nov 14 '17 at 05:35
  • Because if you could do something like `aes.IV[0] = 100;`, Aes class wouldn't be able to handle the change. In general, properties returning arrays are not considered to be a good practice. You can find many articles talking about this, like [this one](https://blogs.msdn.microsoft.com/ericlippert/2008/09/22/arrays-considered-somewhat-harmful/) – Mike Mat Nov 14 '17 at 05:43