2015-10-04 43 views
0

我想在另一個加密算法中使用AES,因此我需要在for循環中一次加密單個128位塊。如何使用AES加密單個塊?

但是MSDN上顯示某些加密類(如RijndaelManaged)用法的示例利用IO流與ICryptoTransform一起將整個明文直接轉換爲密文。

但我認爲這可能對整個長明文是好的,但是如果我只在for循環內部的單個塊上工作,那麼使用這三個流會導致不必要的開銷?有其他方法嗎?

回答

0

根據這一blog post

」 ......使用ICryptoTransform的接口的TransformBlock方法。 這種方法不正是底層 塊加密(AES在我們的例子)的一個區塊轉換,有爲了得到一致的AES塊加密/解密,必須消除與初始矢量(IV)的XOR,這可以通過使用ECB模式或使用ECB模式來實現具有初始IV = 0^{128}的CBC模式「

private static byte[] AES_encrypt_block(byte[] plainText, byte[] Key) 
{ 
    byte[] output_buffer = new byte[plainText.Length]; 

    using (AesManaged aesAlg = new AesManaged()) 
    { 
     //If CBC, must initialize IV = O_{128} 
     //aesAlg.Mode = CipherMode.CBC; 
     //aesAlg.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; 
     aesAlg.Mode = CipherMode.ECB; 

     aesAlg.BlockSize = 128; 
     aesAlg.KeySize = 128; 
     aesAlg.Padding = PaddingMode.None; 
     aesAlg.Key = Key; 

     // Create a decrytor to perform the stream transform. 
     ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); 
     encryptor.TransformBlock(plainText, 0, plainText.Length, output_buffer, 0); 
    } 

    return output_buffer; 
} 

private static byte[] AES_Decrypt_block(byte[] cipherText, byte[] Key) 
{ 
    // Declare the string used to hold the decrypted text. 
    byte[] output_buffer = new byte[cipherText.Length]; 

    using (AesManaged aesAlg = new AesManaged()) 
    { 
     //If CBC, must initialize IV = O_{128} 
     //aesAlg.Mode = CipherMode.CBC; 
     //aesAlg.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; 
     aesAlg.Mode = CipherMode.ECB; 

     aesAlg.BlockSize = 128; 
     aesAlg.KeySize = 128; 
     aesAlg.Padding = PaddingMode.None; 
     aesAlg.Key = Key; 

     // Create a decrytor to perform the stream transform. 
     ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); 
     decryptor.TransformBlock(cipherText, 0, cipherText.Length, output_buffer, 0); 
    } 

    return output_buffer; 
}