2016-11-25 18 views
1

我注意到下面的代碼中有以下奇怪的行爲,如果我將Key設置在對象初始值設定項中,它會生成一個隨機密鑰並且不會設置我的密鑰。這是一個小故障?在RijndaelManaged施工期間的奇怪行爲

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

它沒有錯誤。看源代碼

這是Key屬性。

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 
     }; 
+0

我想按定義它不是一個錯誤..但我仍然覺得這是一個奇怪的實現。沒有反映你永遠不會指望會發生。它違背了對象初始化的規則。加上它只是感到骯髒有一個財產偷偷取消另一個。 – drowhunter

+0

由於這些屬性是「公共虛擬」,因此您可以創建自己的類,從「RijndaelManaged」繼承並覆蓋「Key」和「KeySize」。但我會首先尋找它爲什麼以這種方式實施的原因。也許KeyValue有不同的'KeySizeValue'引入了一些其他的錯誤,甚至運行時錯誤等。@drowhunter –

+1

是有道理的,但它引發的問題..如果關鍵數組和密鑰大小需要匹配爲什麼甚至允許它們是根本不同?對我來說似乎很差邏輯。 – drowhunter