RijndaelManaged 施工期间的奇怪行为

Strange behaviour during RijndaelManaged construction

我注意到以下代码中的以下奇怪行为,如果我在对象初始值设定项中设置密钥,它会生成一个随机密钥并且不会设置我的密钥。这是故障吗?

var algorithm = new RijndaelManaged
{
    Mode = CipherMode.CBC,
    Key = keyBytes,        //if i set the keyBytes here
    KeySize = _keySize,
    IV = Encoding.ASCII.GetBytes(_initVector),
    BlockSize = 128,
    Padding = PaddingMode.Zeros
}; // Set encryption mode to Cipher Block Chaining   

bool wtf= algorithm.Key.AreEqual(keyBytes);

if (!wtf) // <!-- the Key is not the same here
{
    algorithm.Key = keyBytes; // so i end up having to set it again here so that i can decrypt properly
}

这不是错误。查看源码

这是钥匙 属性。

    public virtual byte[] Key {
        get { 
            if (KeyValue == null) GenerateKey();
            return (byte[]) KeyValue.Clone();
        }
        set { 
            if (value == null) throw new ArgumentNullException("value");
            Contract.EndContractBlock();
            if (!ValidKeySize(value.Length * 8))
                throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeySize"));

            // must convert bytes to bits
            KeyValue = (byte[]) value.Clone(); // your byte[] will be set
            KeySizeValue = value.Length * 8;   // key size will be set too
        }
    }

这是 KeySize 属性。

public virtual int KeySize {
    get { return KeySizeValue; }
    set {
        if (!ValidKeySize(value))
            throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeySize"));

        KeySizeValue = value;
        KeyValue = null; // here keyvalue becomes null
    }
}

那是因为你在设置 KeyValue 之后设置了 KeySize,所以你遇到了这个问题。

我认为你不应该设置KeySize 因为它会自动设置,你可以在源代码中看到。如果你设置 KeySize 你的 Key 由于任何原因被实施变为空。

var algorithm = new RijndaelManaged
        {
            Mode = CipherMode.CBC,
            Key = keyBytes,
            // KeySize = _keySize, // remove this
            IV = Encoding.ASCII.GetBytes(_initVector),
            BlockSize = 128,
            Padding = PaddingMode.Zeros
        };