前言
base64加密解密示例和代码:https://blog.csdn.net/weixin_43992507/article/details/108791605
使用jquery.base64.js解密时,中文出现乱码,如下处理
/**
* --------------------------------------------------------------------------------------------------------------------
* 解密例子
*/
function test(value) {
// 解密前
console.log("解密前", value)
var data = $.base64.decode(value, "utf-8");// base64 解密
console.log("解密后1【乱码】:", data)
data = utf8To16(data); // 再次调用utf-8转utf-16即可转码成功
console.log("解密后2【正常】:", data)
}
/**
* --------------------------------------------------------------------------------------------------------------------
* utf8转为utf16
* @param str
* @returns {string}
*/
function utf8To16(str) {
var out, i, len, c;
var char2, char3;
out = "";
len = str.length;
i = 0;
while (i < len) {
c = str.charCodeAt(i++);
switch (c >> 4) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
// 0xxxxxxx
out += str.charAt(i - 1);
break;
case 12:
case 13:
// 110x xxxx 10xx xxxx
char2 = str.charCodeAt(i++);
out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
break;
case 14:
// 1110 xxxx 10xx xxxx 10xx xxxx
char2 = str.charCodeAt(i++);
char3 = str.charCodeAt(i++);
out += String.fromCharCode(((c & 0x0F) << 12) |
((char2 & 0x3F) << 6) |
((char3 & 0x3F) << 0));
break;
}
}
return out;
}
/**
* --------------------------------------------------------------------------------------------------------------------
* utf16转为utf8
* @param str
* @returns {string}
*/
function utf16to8(str) {
var out, i, len, c;
out = "";
len = str.length;
for (i = 0; i < len; i++) {
c = str.charCodeAt(i);
if ((c >= 0x0001) && (c <= 0x007F)) {
out += str.charAt(i);
} else if (c > 0x07FF) {
out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
} else {
out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
}
}
return out;
}