“Padding is invalid and cannot be removed” using AesManaged

前端 未结 6 879
傲寒
傲寒 2020-11-29 04:55

I\'m trying to get simple encryption/decryption working with AesManaged, but I keep getting an exception when trying to close the decryption stream. The string here gets en

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 05:32

    For whats its worth, I'll document what I faced. I was trying to read the encryptor memory stream before the CryptoStream was closed. I know it was naive and I wasted a day debugging it.

        public static byte[] Encrypt(byte[] buffer, byte[] sessionKey, out byte[] iv)
        {
            byte[] encrypted;
            iv = null;
            using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider { Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 })
            {
                aesAlg.Key = sessionKey;
                iv = aesAlg.IV;
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(sessionKey, iv);
    
                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        csEncrypt.Write(buffer, 0, buffer.Length);
    
                        //This was not closing the cryptostream and only worked if I called FlushFinalBlock()
                        //encrypted = msEncrypt.ToArray(); 
                    }
    
                    encrypted = msEncrypt.ToArray();
    
                    return encrypted;
                }
            }
        }
    

    Moving the encryptor memory stream read after the cypto stream was closed solved the problem. As Cheeso mentioned. You don't need to call the FlushFinalBlock() if you're using the using block.

提交回复
热议问题