JavaScript字符串加密解密函数
Javascript默认没有编加密解密函数,需要手动编写。
如下是完整的字符串加解密函数,用到charCodeAt()、fromCharCode()和encodeURIComponent()函数。
先上代码,三个函数说明请看后面。
/** *加密函数 *@paramstr待加密字符串 *@returns{string} */ functionstr_encrypt(str){ varc=String.fromCharCode(str.charCodeAt(0)+str.length); for(vari=1;i<str.length;i++){ c+=String.fromCharCode(str.charCodeAt(i)+str.charCodeAt(i-1)); } returnencodeURIComponent(c); } /** *解密函数 *@paramstr待解密字符串 *@returns{string} */ functionstr_decrypt(str){ str=decodeURIComponent(str); varc=String.fromCharCode(str.charCodeAt(0)-str.length); for(vari=1;i<str.length;i++){ c+=String.fromCharCode(str.charCodeAt(i)-c.charCodeAt(i-1)); } returnc; }
函数说明:
- charCodeAt():返回指定位置的字符的Unicode编码。这个返回值是0-65535之间的整数。
- fromCharCode():接受一个指定的Unicode值,然后返回一个字符串。
- encodeURIComponent():把字符串作为URI组件进行编码。
- decodeURIComponent():对encodeURIComponent()函数编码的URI进行解码。
参考地址:
- JAVASCRIPT加密解密终级指南