views:

27

answers:

1

This MESSED ME UP hard. I thought i was setting the key but i was not. No exceptions, nothing happen except bad results. Why is there a setter if everything is ignored and no exceptions are thrown when i attempt to write? What is the point of the setter on the Keys property?

When i do the below Key value are not changed. After an hour when i realize what was happening i wrote the loop to verify. I also tried aes.Key[0] = val; var b = val == aes.Key[0]; (and messed with it in immediate mode).

Why does it have this behavior?

Array.Copy(myKey, aes.Key, aes.Key.Length);

int i = 0;
foreach (var v in aes.Key)
{
    var b = myKey[i++] == v;
    if (!b)
        b = b;
}
+2  A: 

Well, for one thing, you're not using the setter. What you're doing is using the getter (which grabs a copy of the key), and setting individual bytes in the copy of the key array returned from the getter (which will not affect the internal state of the AesCryptoServiceProvider).

If you want the setter to work correctly, create a new byte array and set the property:

byte[] newKey = new byte[aes.KeySize / 8];
// generate your key...
aes.Key = newKey;

Response to comment:

Your example is entirely in managed code and you're returning a direct reference to the byte array DummyArray explicitly, so naturally you can set any index you choose because you've elected to return the reference. However, there is no requirement that says you must return a reference to the byte array (this is an implementation detail).

The managed CSPs are simply wrapping calls to the unmanaged CAPI, so when the data is marshalled, all you're getting is a copy of the actual data.

John Rasch
I am getting a COPY!?! Why? With this code below DummyArray is properly set like expected. func() { ... d.Key[4]=5; DummyArray[4] = 5; } Byte[] DummyArray_ = new Byte[10]; Byte[] DummyArray { get { return DummyArray_; } set { DummyArray = value; } }
acidzombie24