填充无效,并且在解密AES时无法删除

时间:2018-06-20 16:29:41

标签: c# .net encryption cryptography aes

我面临AES加密的奇怪问题,解密时出错。

解密时出错:

  

填充无效,无法删除

加密方法:

log4j.appender.DB.URL = jdbc:mysql://1.1.1.1/mydb
log4j.appender.DB.user = myuser
log4j.appender.DB.password = mypass

解密方法:

private static string Encrypt(string plainText, byte[] key)
        {
            // Check arguments.
            if (plainText == null || plainText.Length <= 0)
                throw new ArgumentNullException("plainText");
            if (key == null || key.Length <= 0)
                throw new ArgumentNullException("Key");

            byte[] encrypted;
            // Create an Aes object
            // with the specified key and IV.
            using (Aes aesAlg = Aes.Create())
            {
                Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes("SharedPassword", key);

                aesAlg.Key = deriveBytes.GetBytes(aesAlg.KeySize/8);
                //aesAlg.IV = iv;
                aesAlg.GenerateIV();

                // Create a decrytor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);


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

我已经尝试了很多解决方法,如下所述,但是没有一个起作用。 AES decrypt fails with "Padding is invalid and cannot be removed"

C#: AES error: Padding is invalid and cannot be removed. Same key and everything, help

我不明白代码有什么问题。

0 个答案:

没有答案