javascript将url中的参数加密解密代码
今天在做一个老项目时,遇到一个需求,在javascript将url中的参数加密解密,从网上找发现了这段有用的代码:
<SCRIPTLANGUAGE="JavaScript">
<!--Begin
functionEncrypt(str,pwd){
if(str=="")return"";
str=escape(str);
if(!pwd||pwd==""){varpwd="1234";}
pwd=escape(pwd);
if(pwd==null||pwd.length<=0){
alert("Pleaseenterapasswordwithwhichtoencryptthemessage.");
returnnull;
}
varprand="";
for(varI=0;I<pwd.length;I++){
prand+=pwd.charCodeAt(I).toString();
}
varsPos=Math.floor(prand.length/5);
varmult=parseInt(prand.charAt(sPos)+prand.charAt(sPos*2)+prand.charAt(sPos*3)+prand.charAt(sPos*4)+prand.charAt(sPos*5));
varincr=Math.ceil(pwd.length/2);
varmodu=Math.pow(2,31)-1;
if(mult<2){
alert("Algorithmcannotfindasuitablehash.Pleasechooseadifferentpassword./nPossibleconsiderationsaretochooseamorecomplexorlongerpassword.");
returnnull;
}
varsalt=Math.round(Math.random()*1000000000)%100000000;
prand+=salt;
while(prand.length>10){
prand=(parseInt(prand.substring(0,10))+parseInt(prand.substring(10,prand.length))).toString();
}
prand=(mult*prand+incr)%modu;
varenc_chr="";
varenc_str="";
for(varI=0;I<str.length;I++){
enc_chr=parseInt(str.charCodeAt(I)^Math.floor((prand/modu)*255));
if(enc_chr<16){
enc_str+="0"+enc_chr.toString(16);
}else
enc_str+=enc_chr.toString(16);
prand=(mult*prand+incr)%modu;
}
salt=salt.toString(16);
while(salt.length<8)salt="0"+salt;
enc_str+=salt;
returnenc_str;
}
functionDecrypt(str,pwd){
if(str=="")return"";
if(!pwd||pwd==""){varpwd="1234";}
pwd=escape(pwd);
if(str==null||str.length<8){
alert("Asaltvaluecouldnotbeextractedfromtheencryptedmessagebecauseit'slengthistooshort.Themessagecannotbedecrypted.");
return;
}
if(pwd==null||pwd.length<=0){
alert("Pleaseenterapasswordwithwhichtodecryptthemessage.");
return;
}
varprand="";
for(varI=0;I<pwd.length;I++){
prand+=pwd.charCodeAt(I).toString();
}
varsPos=Math.floor(prand.length/5);
varmult=parseInt(prand.charAt(sPos)+prand.charAt(sPos*2)+prand.charAt(sPos*3)+prand.charAt(sPos*4)+prand.charAt(sPos*5));
varincr=Math.round(pwd.length/2);
varmodu=Math.pow(2,31)-1;
varsalt=parseInt(str.substring(str.length-8,str.length),16);
str=str.substring(0,str.length-8);
prand+=salt;
while(prand.length>10){
prand=(parseInt(prand.substring(0,10))+parseInt(prand.substring(10,prand.length))).toString();
}
prand=(mult*prand+incr)%modu;
varenc_chr="";
varenc_str="";
for(varI=0;I<str.length;I+=2){
enc_chr=parseInt(parseInt(str.substring(I,I+2),16)^Math.floor((prand/modu)*255));
enc_str+=String.fromCharCode(enc_chr);
prand=(mult*prand+incr)%modu;
}
returnunescape(enc_str);
}
// End-->
</script>
以后碰到加密解密问题,直接将上述代码写成一个js文件,就搞定。省事了。。。。