填充无效且无法删除使用“AesManaged”C#解密字符串时出现exception

请建议我在哪里需要更新/重构代码以摆脱exception。 我尝试使用以下代码解密加密字符串时出现exception。

以下行抛出exception

using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { // Read the decrypted bytes from the decrypting stream // and place them in a string. plaintext = srDecrypt.ReadToEnd(); } public string EncryptAuthenticationTokenAes(string plainText) { byte[] encrypted; // Create an AesManaged object // with the specified key and IV. using (AesManaged aesAlg = new AesManaged()) { // Create a decrytor to perform the stream transform. ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); aesAlg.Padding = PaddingMode.None; // Create the streams used for encryption. using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { //Write all data to the stream. swEncrypt.Write(plainText); } encrypted = msEncrypt.ToArray(); } } } // Return the encrypted bytes from the memory stream. return Convert.ToBase64String(encrypted); } public string DecryptPasswordAes(string encryptedString) { //Convert cipher text back to byte array byte[] cipherText = Convert.FromBase64String(encryptedString); // Declare the string used to hold // the decrypted text. string plaintext = null; // Create an AesManaged object // with the specified key and IV. using (AesManaged aesAlg = new AesManaged()) { // Create a decrytor to perform the stream transform. ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); aesAlg.Padding = PaddingMode.None; // Create the streams used for decryption. using (MemoryStream msDecrypt = new MemoryStream(cipherText)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { // Read the decrypted bytes from the decrypting stream // and place them in a string. plaintext = srDecrypt.ReadToEnd(); } } } } return plaintext; } 

使用CryptoStream时很标准的错误,你忘了强制它加密流的最后几个字节。 它将字节保留在内部缓冲区中,直到它们到达足以发出块为止。 您必须强制退出最后几个字节。 固定:

  using (var msEncrypt = new MemoryStream()) using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) using (var swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(plainText); csEncrypt.FlushFinalBlock(); encrypted = msEncrypt.ToArray(); } 

解密时遇到exception,因为加密缺少最后的填充。 真正的问题是由using语句引起的,如果在CryptoStream关闭之前等待获取加密的字节,则不会出现此问题。 但这不能很好地工作,因为StreamWriter上的using语句也会关闭CryptoStream和MemoryStream。 明确使用FlushFinalBlock()是最好的解决方法。