Rijndaelmanman建筑期间的奇怪行为



我注意到以下代码中的以下奇怪行为,如果我在对象初始化器中设置键,它会生成一个随机键,而不会设置我的键。这是小故障吗?

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,则出于任何原因实现将变为null。

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

相关内容

  • 没有找到相关文章

最新更新