RijndaelManaged构建期间的奇怪行为

时间:2016-11-25 20:29:25

标签: c# rijndaelmanaged

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

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
}

1 个答案:

答案 0 :(得分:1)

它不是错误。查看源代码

这是关键属性。

    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
    }
}

那是因为您在设置KeySize之后设置KeyValue因此会遇到问题。

我认为您不应该设置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
        };