js加密浅谈
当在页面中用js对汉字进行加密
<script language="javascript" type="text/javascript">
function escap()
{
var strurl;//用于http的网络路径
strurl = "Default2.aspx?X="+encodeURIComponent("骄傲");
window.open(strurl);
}
</script>
<input id="Button1" type="button" value="button" onclick="escap()" />
当按照这个传递的路径打开新的页面时,在后台 PageLoad 中用:
if(Request["X"].ToString().Trim()!=null)
{
string str = System.Web.HttpUtility.UrlDecode(Request.QueryString["X"].ToString().Trim());
this.Label1.Text = str;
}
其中 System.Web.HttpUtility.UrlDecode 是C#后台解码的方法
escape和unescape是函数与反函数的关系
对 String 对象编码以便它们能在所有计算机上可读,
escape(charString)
必选项 charstring 参数是要编码的任意 String 对象或文字。
说明
escape 方法返回一个包含了 charstring 内容的字符串值( Unicode 格式)。所有空格、标点、重音符号以及其他非 ASCII 字符都用 %xx 编码代替,其中 xx 等于表示该字符的十六进制数。例如,空格返回的是 "%20" 。
字符值大于 255 的以 %uxxxx 格式存储。
unescape 方法
解码用 escape 方法进行了编码的 String 对象。
unescape(charstring)
必选项 charstring 参数是要解码的 String 对象。
说明
unescape 方法返回一个包含 charstring 内容的字符串值。所有以 %xx 十六进制形式编码的字符都用 ASCII 字符集中等价的字符代替。
以 %uxxxx 格式(Unicode 字符)编码的字符用十六进制编码 xxxx 的 Unicode 字符代替.
这两个函数的功能是用来将字符进行编码我反编码(解码),其主要用途在使用cookie时经常用到这两个函数,因为在要对cookie进行写入时,那些特殊字符(符号和汉字)需要进行编码才能写入,所以在读取时就需要用到unescape函数进行解码再显示,下面是一点例子:
//----------------------------------------------------------------------------
// Set a cookie given a name, value and expiration date.
//----------------------------------------------------------------------------
function setCookie (name, value,len) {
var date = new Date ();
len = len || 86400 * 1000 * 2;
date.setTime (date.getTime() + len * 1000);
document.cookie = name + "=" + escape(value) + "; expires=" + date.toGMTString() + "; path=/";
if(document.cookie.length > 1024){
deleteCookie(name);
}
}
//----------------------------------------------------------------------------
// Returns the value of the named cookie.
//----------------------------------------------------------------------------
function getCookie(name) {
var search;
search = name + "=";
offset = document.cookie.indexOf(search) ;
if (offset != -1) {
offset += search.length;
end = document.cookie.indexOf(";", offset);
if (end == -1)
end = document.cookie.length;
return unescape(document.cookie.substring(offset, end));
}
else
return "";
}
浙公网安备 33010602011771号