.net RijndaelManaged "Padding is invalid and cannot be removed" 仅在生产中解密时发生

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2116607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 13:50:07  来源:igfitidea点击:

RijndaelManaged "Padding is invalid and cannot be removed" that only occurs when decrypting in production

.netcryptographyaesencryptionrijndaelmanaged

提问by Nick Allen

I know other questions have been asked on this but none so far have provided a solution or are exactly the issue I have.

我知道其他问题已经被问到了,但到目前为止还没有提供解决方案或者正是我遇到的问题。

The class below handles the encryption and decryption of strings, the key and vector passed in are ALWAYS the same.

下面的类处理字符串的加密和解密,传入的密钥和向量始终相同。

The strings being encrypted and decrypted are always numbers, most work but the occasional one fails when decrypting (but only on the production server). I should mention that both local and production environments are in IIS6 on Windows Server 2003, the code that uses the class sits in a .ashx handler. The example that fails on the production server is "0000232668"

被加密和解密的字符串总是数字,大多数工作但偶尔会在解密时失败(但仅在生产服务器上)。我应该提到本地和生产环境都在 Windows Server 2003 上的 IIS6 中,使用该类的代码位于 .ashx 处理程序中。在生产服务器上失败的例子是“0000232668”

The error message is

错误信息是

System.Security.Cryptography.CryptographicException: Padding is invalid and cannot be removed. at System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode paddingMode, Boolean fLast)

System.Security.Cryptography.CryptographicException:填充无效且无法删除。在 System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode paddingMode, Boolean fLast)

And for the code

对于代码

 public class Aes
    {
        private byte[] Key;
        private byte[] Vector;

        private ICryptoTransform EncryptorTransform, DecryptorTransform;
        private System.Text.UTF8Encoding UTFEncoder;

        public Aes(byte[] key, byte[] vector)
        {
            this.Key = key;
            this.Vector = vector;

            // our encyption method
            RijndaelManaged rm = new RijndaelManaged();

            rm.Padding = PaddingMode.PKCS7;

            // create an encryptor and decyptor using encryption method. key and vector
            EncryptorTransform = rm.CreateEncryptor(this.Key, this.Vector);
            DecryptorTransform = rm.CreateDecryptor(this.Key, this.Vector);

            // used to translate bytes to text and vice versa
            UTFEncoder = new System.Text.UTF8Encoding();
        }

        /// Encrypt some text and return a string suitable for passing in a URL. 
        public string EncryptToString(string TextValue)
        {
            return ByteArrToString(Encrypt(TextValue));
        }

        /// Encrypt some text and return an encrypted byte array. 
        public byte[] Encrypt(string TextValue)
        {
            //Translates our text value into a byte array. 
            Byte[] bytes = UTFEncoder.GetBytes(TextValue);
            Byte[] encrypted = null;

            //Used to stream the data in and out of the CryptoStream. 
            using (MemoryStream memoryStream = new MemoryStream())
            {                
                using (CryptoStream cs = new CryptoStream(memoryStream, EncryptorTransform, CryptoStreamMode.Write))
                {
                    cs.Write(bytes, 0, bytes.Length);                    
                }

                encrypted = memoryStream.ToArray();                
            }

            return encrypted;
        }

        /// The other side: Decryption methods 
        public string DecryptString(string EncryptedString)
        {
            return Decrypt(StrToByteArray(EncryptedString));
        }

        /// Decryption when working with byte arrays.     
        public string Decrypt(byte[] EncryptedValue)
        {
            Byte[] decryptedBytes = null;

            using (MemoryStream encryptedStream = new MemoryStream())
            {
                using (CryptoStream decryptStream = new CryptoStream(encryptedStream, DecryptorTransform, CryptoStreamMode.Write))
                {
                    decryptStream.Write(EncryptedValue, 0, EncryptedValue.Length);
                }

                decryptedBytes = encryptedStream.ToArray();
            }

            return UTFEncoder.GetString(decryptedBytes);
        }

        /// Convert a string to a byte array.  NOTE: Normally we'd create a Byte Array from a string using an ASCII encoding (like so). 
        //      System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); 
        //      return encoding.GetBytes(str); 
        // However, this results in character values that cannot be passed in a URL.  So, instead, I just 
        // lay out all of the byte values in a long string of numbers (three per - must pad numbers less than 100). 
        public byte[] StrToByteArray(string str)
        {
            if (str.Length == 0)
                throw new Exception("Invalid string value in StrToByteArray");

            byte val;
            byte[] byteArr = new byte[str.Length / 3];
            int i = 0;
            int j = 0;
            do
            {
                val = byte.Parse(str.Substring(i, 3));
                byteArr[j++] = val;
                i += 3;
            }
            while (i < str.Length);
            return byteArr;
        }

        // Same comment as above.  Normally the conversion would use an ASCII encoding in the other direction: 
        //      System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); 
        //      return enc.GetString(byteArr);     
        public string ByteArrToString(byte[] byteArr)
        {
            byte val;
            string tempStr = "";
            for (int i = 0; i <= byteArr.GetUpperBound(0); i++)
            {
                val = byteArr[i];
                if (val < (byte)10)
                    tempStr += "00" + val.ToString();
                else if (val < (byte)100)
                    tempStr += "0" + val.ToString();
                else
                    tempStr += val.ToString();
            }
            return tempStr;
        }

EDIT:Thankyou for all of your help however your answers did not un-cover the problem, which turned out to be something stupidly simple. I was generating an encrypted string on one server and handing it over to a handler on another server for decrpytion and processing, but it turns out that the results of encryption differ when run on different servers, hence the receiving server could not decrypt it. One of the answers stumbled across the hint at this by accident, which is why I accepted it

编辑:感谢您的所有帮助,但是您的回答并没有解决问题,结果证明这是一件非常简单的事情。我在一台服务器上生成了一个加密字符串,然后将它交给另一台服务器上的处理程序进行解密和处理,但事实证明,在不同的服务器上运行时,加密的结果不同,因此接收服务器无法对其进行解密。其中一个答案偶然发现了这个暗示,这就是我接受它的原因

采纳答案by David M

You will sometimes get a message about invalid padding when encryption and decryption for whatever reason have not used the same key or initialisation vector. Padding is a number of bytes added to the end of your plaintext to make it up to a full number of blocks for the cipher to work on. In PKCS7 padding each byte is equal to the number of bytes added, so it can always be removed after decryption. Your decryption has led to a string where the last nbytes are not equal to the value nof the last byte (hope that sentence makes sense). So I would double check all your keys.

当加密和解密由于任何原因没有使用相同的密钥或初始化向量时,您有时会收到一条关于无效填充的消息。填充是添加到明文末尾的许多字节,以使其成为密码可以处理的完整数量的块。在 PKCS7 中填充每个字节等于添加的字节数,因此它总是可以在解密后删除。您的解密导致了一个字符串,其中最后n个字节不等于最后一个字节的值n(希望这句话有意义)。所以我会仔细检查你所有的钥匙。

Alternatively, in your case, I would suggest making sure that you create and dispose an instance of RijndaelManagedTransformfor each encryption and decryption operation, initialising it with the key and vector. This problem could very well be caused by reusing this transform object, which means that after the first use, it is no longer in the right initial state.

或者,在您的情况下,我建议您确保RijndaelManagedTransform为每个加密和解密操作创建并处理一个实例,并使用密钥和向量对其进行初始化。这个问题很可能是由于重用这个变换对象引起的,这意味着第一次使用后,它不再处于正确的初始状态。

回答by Dave Cluderay

I tend to explicitly call the FlushFinalBlockmethod on CryptoStream before closing it. That would mean doing the following in your encrypt method:

我倾向于在关闭它之前显式调用CryptoStream 上的FlushFinalBlock方法。这意味着在您的加密方法中执行以下操作:

using (CryptoStream cs = new CryptoStream(memoryStream, EncryptorTransform, CryptoStreamMode.Write))
{
    cs.Write(bytes, 0, bytes.Length);
    cs.FlushFinalBlock();        
}

If you don't do this, it may be that the encrypted data is being truncated - this would result in an "invalid padding" scenario. Padding is always present when using PKCS7, even if the data being encrypted is aligned to the block length of the cipher.

如果您不这样做,则可能是加密数据被截断 - 这将导致“无效填充”情况。使用 PKCS7 时始终存在填充,即使被加密的数据与密码的块长度对齐。

回答by Sani Singh Huttunen

this results in character values that cannot be passed in a URL

这会导致无法在 URL 中传递的字符值

Is there reason why you are using your own encoding, StrToByteArray, instead of Base64encoding?

您是否有理由使用自己的编码StrToByteArray,而不是Base64编码?

If you make these changes:

如果您进行这些更改:

public string EncryptToString(string TextValue)
{
  return Convert.ToBase64String(Encrypt(TextValue));
}

public string DecryptToString(string TextValue)
{
  return Decrypt(Convert.FromBase64String(TextValue));
}

then things should work a lot better.

那么事情应该会好很多。

Edit:
Regarding problem with ToBase64String and QueryString:
If you do your own QueryString parsing then you need to make sure you only Split on the first =-sign.

编辑:
关于 ToBase64String 和 QueryString 的问题:
如果您进行自己的 QueryString 解析,那么您需要确保仅在第一个 = 符号上拆分。

var myURL = "http://somewhere.com/default.aspx?encryptedID=s9W/h7Sls98sqw==&someKey=someValue";
var myQS = myURL.SubString(myURL.IndexOf("?") + 1);
var myKVPs = myQS.Split("&");
foreach (var kvp in myKVPs) {
  // It is important you specify a maximum number of 2 elements
  // since the Base64 encoded string might contain =-signs.
  var keyValue = kvp.Split("=", 2);
  var key = keyValue[0];
  var value = keyValue[1];
  if (key == "encryptedID")
    var decryptedID = myAES.DecryptToString(value);
}

This way you don't need to replace any characters in your QueryString when it's Base64 encoded.

这样,当 QueryString 为 Base64 编码时,您无需替换其中的任何字符。