关于URL参数的加密
URL参数一般都需要采取加密技术,来隐藏一些敏感信息。方法如下:
1.把数据绑定到GridView控件添加一个超链接和一个模板字段,模板字段的链接参被加密。
<asp:GridView ID="GridView1" runat="server" >
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:HyperLinkField DataNavigateUrlFields="AccountID,AccountCode"
DataNavigateUrlFormatString="DemoViewState.htm?id={0}&Code={1}"
DataTextField="AccountID" HeaderText="连接" />
<asp:TemplateField HeaderText="字符串">
<ItemTemplate>
<a href="DemoViewState.htm?id=<%# Helper.Encode(DataBinder.Eval(Container.DataItem,"AccountCode").ToString(),"sseertyu") %>"><%# DataBinder.Eval(Container.DataItem,"AccountCode") %></a>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
2.关键看看加密类吧,调用Helper类可完成加密。
public class Helper
{
public Helper()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
public static string Decode(string str, string key)//解密函数
{
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));
provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));
byte[] buffer = new byte[str.Length / 2];
for (int i = 0; i < (str.Length / 2); i++)
{
int num2 = Convert.ToInt32(str.Substring(i * 2, 2), 0x10);
buffer[i] = (byte)num2;
}
MemoryStream stream = new MemoryStream();
CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write);
stream2.Write(buffer, 0, buffer.Length);
stream2.FlushFinalBlock();
stream.Close();
return Encoding.GetEncoding("GB2312").GetString(stream.ToArray());
}
public static string Encode(string str, string key)//加密函数
{
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));
provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));
byte[] bytes = Encoding.UTF8.GetBytes(str);
MemoryStream stream = new MemoryStream();
CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);
stream2.Write(bytes, 0, bytes.Length);
stream2.FlushFinalBlock();
StringBuilder builder = new StringBuilder();
foreach (byte num in stream.ToArray())
{
builder.AppendFormat("{0:X2}", num);
}
stream.Close();
return builder.ToString();
}
}