当前位置: 动力学知识库 > 问答 > 编程问答 >

.net - 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]; (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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: