0

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

默认块大小是 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);
            }
        }
4

2 回答 2

1

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

于 2013-05-29T14:32:55.627 回答
0

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

于 2013-05-29T18:54:14.967 回答