c#中Base-64 char数组错误的长度无效

时间:2015-11-12 13:33:25

标签: c# asp.net

在远程服务器中,我已将此redirect添加到我的网络服务器:

index.aspx网页上querystring UserNumber 的值加密

protected void Page_Load(object sender, EventArgs e)
{
    Response.Redirect("http://.../default.aspx?UserNumber=" + Encrypt(Request.QueryString["UserNumber"].ToString().Trim()));
}

网页index.aspx重定向到身份验证页面,其中querystring UserNumber 的值已解密

我运行了多次测试,但我对此 UserNumber a425033A425033有疑问。

UserNumber 的值为a425033A425033时,用于身份验证的网页会显示以下错误:

enter image description here

错误是:

Invalid length for a Base-64 char array

我的代码如下。

请帮帮我。

提前谢谢。

private string Encrypt(string clearText)
{
    string EncryptionKey = "Some String";

    if (Request.QueryString["UserNumber"] != null)
    {
        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { /*Some Bytes*/ });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                clearText = Convert.ToBase64String(ms.ToArray());
            }
        }
        return clearText;
    }
    else
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(), "Msg", "alert('No user.');window.location='http://.../main.aspx';", true);
        return null;
    }
}

private string Decrypt(string cipherText)
{
    string EncryptionKey = "Some String";

    if (Request.QueryString["UserNumber"] != null)
    {
        byte[] cipherBytes = Convert.FromBase64String(cipherText);

        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { /*Some Bytes*/ });
            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();
                }
                cipherText = Encoding.Unicode.GetString(ms.ToArray());
            }
        }
        return cipherText;
    }
    else
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(), "Msg", "alert('No user.');window.location='http://.../main.aspx';", true);
        return null;
    }
}

1 个答案:

答案 0 :(得分:1)

试试这个:

Decrypt(Request.QueryString["UserNumber"].ToString().Replace(" ", "+"))

我希望能帮助您解决问题。