No Padding给出加密数据的长度是无效的异常

时间:2013-05-29 14:28:04

标签: c# encryption aes

我收到的异常是“要加密的数据长度无效”。我知道这是因为输入数据的长度不是块大小的倍数。我仍然是这个加密的新手,所以我有几个问题。

默认的块大小是128正确吗?这不支持256块大小,所以如果我们发送给它的供应商要求,我如何发送256块大小?

如何在不调整填充的情况下使数据的长度正确,因为供应商也不需要填充?

        string currentTime = DateTime.UtcNow.ToString("yyyyMMddHHmmss");
        string userId = "";
        string baseURL = ConfigurationManager.AppSettings["baseURL"];
        string config = ConfigurationManager.AppSettings["keyType"];
        string key = "";

        //sets the base URL to use, parameters will still need to be configured.
        if (config == "Q")
            key = "KEY";
        else if (config == "P")
            key = "KEY";

        if(Request.Headers.AllKeys.Contains("memberof"))
        {
            if(Request.Headers["memberof"].Contains("GROUP-NAME"))
            {
                if (Request.Headers.AllKeys.Contains("user"))
                    userId = "tvs2"; //will come from header always 4 characters
                else
                    return;
                string[] keyArray = key.Split(',');

                sbyte[] sBytes = new sbyte[keyArray.Length];
                for (int i = 0; i < keyArray.Length; i++)
                {
                    sBytes[i] = Convert.ToSByte(keyArray[i]);
                }
                byte[] bytes = (byte[])(Array)sBytes;

                AesManaged tdes = new AesManaged();
                tdes.Key = bytes;
                tdes.Mode = CipherMode.CBC;
                tdes.Padding = PaddingMode.None;
                ICryptoTransform crpyt = tdes.CreateEncryptor();
                byte[] userData = Encoding.UTF8.GetBytes(userId);
                byte[] dateData = Encoding.UTF8.GetBytes(currentTime);
                byte[] userCipher = crpyt.TransformFinalBlock(userData, 0, userData.Length);
                byte[] dateCipher = crpyt.TransformFinalBlock(dateData, 0, dateData.Length);

                string encryptedUser = Convert.ToBase64String(userCipher);
                string encrpytedDate = Convert.ToBase64String(dateCipher);

                string url = baseURL
                    + "username="
                    + encryptedUser + "&timestamp="
                    + encrpytedDate;

                Response.Redirect(url);
            }
        }

2 个答案:

答案 0 :(得分:1)

使用流密码模式而不是块密码模式。也就是说,尝试AES-CTR而不是AES-CBC。

答案 1 :(得分:0)

如果你可以使用CipherMode.CTS(CipherText Stealing)代替CBC,你应该能够加密任意长度的数据(不一定是块大小的倍数),产生的输出长度与输入