开发者

Why does set key not do anything in AES/SymmetricAlgorithm?

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]; 开发者_C百科(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;
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜