加密:Convert.ToBase64String(); 微软文档:传送门
解密:Convert.FromBase64String(); 微软文档:传送门
我们编写两个方法,用于加密和解密
public string base64Encode(string str) //加密
{
byte[] bt = Encoding.UTF8.GetBytes(str);
return Convert.ToBase64String(bt);
}
{
byte[] bt = Encoding.UTF8.GetBytes(str);
return Convert.ToBase64String(bt);
}
public string base64Decode(string base64str, string codename) //解密
{
byte[] bt = Convert.FromBase64String(base64str);
return Encoding.GetEncoding(codename).GetString(bt);
}return Encoding.GetEncoding(codename).GetString(bt);
知道这两上方法后,我们要怎么操作呢?其实很简单,首先加密,添加一个Default.aspx页面,里面分别放一个TextBox和Button
在Button的Click事件中添加代码:
protected void btnSubmit_Click(object sender, EventArgs e)
{
string base64Code = this.base64Encode(this.txtSource.Text.Trim());
Response.Redirect(string.Format("/TargetPage.aspx?id={0}", base64Code));
}
{
string base64Code = this.base64Encode(this.txtSource.Text.Trim());
Response.Redirect(string.Format("/TargetPage.aspx?id={0}", base64Code));
}
在TargetPage.aspx中添加一个label控件,并在Page_Load事件中添加代码
string base64Code = Request.Params["id"];
lblResult.Text = this.base64Decode(base64Code, "UTF-8");
lblResult.Text = this.base64Decode(base64Code, "UTF-8");
测试结果:
URL地址为:http://localhost:8199/TargetPage.aspx?id=aHR0cDovL3d3dy5jbmJsb2dzLmNvbQ==
页面内容为:http://www.cnblogs.com