2016-11-25 13 views
1

次のコードでは、オブジェクト初期化子にキーを設定してランダムキーを生成し、キーを設定しないと、次のような奇妙な動作が発生しました。これは不具合ですか?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プロパティです。あなたはそのため、あなたが得る問題をKeyValueを設定した後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は、ソースコードのように自動的に設定されるため、設定しないでください。 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 
     }; 
+0

これはバグではありませんが、私はまだそれが奇妙な実装のように感じます。あなたがそれが起こることを決して期待しないであろうことを反映することなくオブジェクトの初期化の規則に反します。それだけで、あるプロパティを秘密に別のプロパティを無効にすることは汚いと感じます。 – drowhunter

+0

これらのプロパティは 'public virtual'であるため、独自のクラスを作成し、' RijndaelManaged'から継承し、 'Key'と' KeySize'をオーバーライドすることができます。しかし、私はまず、なぜこのように実装されたのか理由を探します。おそらく 'KeyValue'と異なる' KeySizeValue'を持つと、他のバグやランタイムエラーなどが発生します。@drowhunter –

+1

はい、意味があります。もしキー配列とキーサイズが一致する必要があるのであれば全く違った設定ですか?私にとっては貧しい論理のようだ。 – drowhunter