如何使用AES获取相同纯文本的不同密文

我目前在C#中使用AesManaged类来加密纯文本。 它工作正常。

但是,每次加密同一条数据时,它都会生成相同的密文。 反正我是否可以调整此行为并为同一条数据生成不同的密文?

我使用AES_256算法和证书在SQL服务器中实现了加密。 该过程与此处的post非常相似: http : //www.codeproject.com/Articles/662187/FIPS-Encryption-Algorithms-and-Implementation-of-A 。 在此过程中,每次加密纯文本时,都会生成不同的密文。

我想要与C#代码相同的效果。 如何实现?

编辑:以下是我实施Yolanda Ruiz建议的方法:

加密

public static string Encrypt(string plainText) { //Check for valid arguments. if (String.IsNullOrEmpty(plainText)) throw new ArgumentNullException("plainText"); List encryptedList; //Create Aes object using (AesManaged aes = new AesManaged()) { aes.Key = Key; aes.GenerateIV(); encryptedList = aes.IV.ToList(); aes.BlockSize = BlockSize; /*Here goes the standard code to encrypt the plain text - refer msdn for that*/ /*Append the encrypted stream to encryptedList*/ } return encryptedList.ToArray().ToBase64(); } 

解码

  public static string Decrypt(string cipherText) { //Check for valid arguments. if (string.IsNullOrEmpty(cipherText)) throw new ArgumentNullException("cipherText"); string plainText; byte[] cipherTextArray = cipherText.FromBase64(); //Create Aes object using (AesManaged aes = new AesManaged()) { aes.Key = Key; aes.BlockSize = BlockSize; aes.IV = cipherTextArray.Take(NoOfBytes).ToArray();//Extract the IV cipherTextArray = cipherTextArray.Skip(NoOfBytes).ToArray();//Extract the actual plain text. /*Here goes the standard code to Decrypt the cipher text - refer msdn for that*/ /*Assign the decrypted stream output to plainText*/ } return plainText; } 

unit testing

  //Arrange string plainText = "Sayan"; //Act string cipherText1 = MyCrypto.Encrypt(plainText); string cipherText2 = Crypto.Encrypt(plainText); string plainText1 = Crypto.Decrypt(cipherText1); string plainText2 = Crypto.Decrypt(cipherText2); //Assert //Check the cipher text is different everytime Assert.AreNotEqual(cipherText1, cipherText2); //Check that every plaintext output should match with the original Assert.AreEqual(plainText, plainText1); Assert.AreEqual(plainText, plainText2); 

这样做的方法是为每个加密使用不同的初始化向量 。

AesManaged中的默认操作模式是CBC 。 在该模式中,当加密明文块时,首先将其与前一个块的加密结果混合。 只要前一个密文块总是不同,这就可以防止两个相似的明文块输出相同的密文。 但是,我们在第一个街区使用了什么呢? 初始化向量。

IV基本上是一个随机块,就好像它是加密在实际的第一个明文块之前的假设明文块的结果。

必须保留IV,以便我们可以将其提供给解密方法。 因为它在语义上是密文块,所以通常将它添加到实际的密文中。 在解密时,您将首先提取第一个密文块( 按原样 ,不进行解密),并将其用作IV来解密后续块。

IV不是秘密。 攻击者将无法从中获取密钥或第一个明文块。 您必须永远不要使用相同的密钥重复使用相同的IV两次,否则您将失去随机化属性。

您要查看的方法是AesManaged.GenerateIV()AesManaged.BlockSize (以位为单位,如果您使用该属性从密文中提取IV字节,请记住它)。

加密算法必须是确定性的(否则无法逆转它们)

如果要获取不同的密文,则必须更改密钥或要加密的数据(或实际算法)。