Padding is invalid and cannot be removed Exception while decrypting string using “AesManaged” C#

后端 未结 1 1816
情歌与酒
情歌与酒 2020-12-07 02:47

Please suggest me where i need to update/refactor the code to get rid of exception. I am getting exception while I try to decrypt the encrypted string using following code.<

相关标签:
1条回答
  • 2020-12-07 03:07

    Pretty standard bug when using CryptoStream, you forgot to force it to encrypt the last bytes of the stream. It keeps bytes in an internal buffer until enough of them arrive to emit a block. You must force the last few bytes out. Fix:

        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();
        }
    

    You got the exception when decrypting it because encrypted is missing the final padding. The real problem is caused by the using statement, you wouldn't have this problem if you waited obtaining the encrypted bytes until after the CryptoStream is closed. But that doesn't work well because the using statement on the StreamWriter also closes the CryptoStream and the MemoryStream. Explicitly using FlushFinalBlock() is the best workaround.

    0 讨论(0)
提交回复
热议问题