在解密期间,Base-64字符数组的长度无效

本文关键字:数组 无效 字符 Base-64 解密 | 更新日期: 2023-09-27 18:06:18

我在登录时使用下面的代码,我得到以下错误

Base-64字符数组或字符串的长度无效。

第24行:byte[] cipherBytes = Convert.FromBase64String(txtpass . text);

 protected void txtlog_Click(object sender, EventArgs e)
    {
        string EncryptionKey = "MAKV2SPBNI99212";
        byte[] cipherBytes = Convert.FromBase64String(txtpas.Text);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(cipherBytes, 0, cipherBytes.Length);
                    cs.Close();
                }
                txtpas.Text = Encoding.Unicode.GetString(ms.ToArray());
                if (u.Login(txtuser.Text, txtpas.Text) == true)
                {
                    UtilityClass.CreateCookie("login", new string[] { "username", "usertypeid" }, new string[] { txtuser.Text, u.UserTypeID.ToString().Trim() }, !chkrem.Checked, Response);
                    Response.Redirect("SiteAdmin/index.aspx");
                }
                else
                {
                    Label1.Text = "“Invalid Username or Password”";
                }
            }
        }
        }

在解密期间,Base-64字符数组的长度无效

考虑一下Base64字符串在做什么。它在6位边界上打破8位字节,并分配一个与这些位的值对应的文本字符。如果您有1个字节,您将有2个Base64字符(加上总是附加在Base64字符串末尾的额外字符)。其中一个Base64字符可以是64位"字母表"中的任何字符,而另一个字符将是4个字符中的一个,具体取决于最后2位的设置。

如果你有2个字节要编码,这16位就变成3个Base64字符,最后一个字符只能来自Base64字母表的后16位(4位)。

以此类推。3字节是24位,需要4个Base64字符来表示它们。但是在什么情况下我们需要5个Base64字符呢?从来没有。3个字节可以容纳4个字符,4个字节需要6个字符。任何长度恰好为5个字符的Base64字符串都不能很好地表示任何整数字节。并且这些无效长度在整个数字范围内经常重复。

这并不是说一个简单的压缩算法不能截断末尾的0位并产生一个5个字符的Base64字符串,但这是不正常的,如果你试图将它转换为字节,将会抛出异常。