使用 AES 的相同加密文本必须产生不同的长度

Same encrypted Text with AES must result in different length

我使用这个示例代码:https://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged.aspx

AESCryptor是我自己的class,原代码来自上面的msdnlink。它只是包装 Decrypt/encrypt 方法而不是更多。

我就是这样调用 decrypt/encrypt 方法的:

string plainText1 = "This is my sample plain text";
string plainText2 = "This is my sample plain text";

// Create a new instance of the AesManaged
// class.  This generates a new key and initialization 
// vector (IV).
using (AesManaged myAes = new AesManaged())
{
    // Encrypt the string to an array of bytes.
    byte[] encrypted = AESCryptor.EncryptStringToBytes_Aes(plainText1, myAes.Key, myAes.IV);

    byte[] encrypted2 = AESCryptor.EncryptStringToBytes_Aes(plainText2, myAes.Key, myAes.IV);

}

我期望的结果是(加密和加密2)字节数组当然具有相同的长度但是被"zeros"填满所以当我用Base64编码字节[]时我得到不同的外观字符串。

我该怎么做?设置 myAes.Padding = PaddingMode.Zeros; 没有帮助。

为了获得相同密钥和明文的不同结果,您需要使用不同的 IV。

从外观上看,要使用单个 AesManaged 实例执行此操作,您需要在两次加密调用之间调用 myAes.GenerateIV()

如果您创建一个 new AesManaged,您将获得一个 new 密钥和一个 new IV免费,说不定也能达到你想要的效果

不要忘记记录您的密钥和 IV,因为没有它们您将无法解密您的消息。