背景
使用uniapp开发微信小程序,因为后端返回参数有加密数据使用的是AES_GCM加密算法,因此使用asmcrypto.js用于解密,微信开发者工具中,代码正常,但是部署上线后出现atob、Buffer 或 TextDecoder为undefind情况
问题代码
- 小程序中不支持
atob
js
// 解码
function base64ToBytes(base64) {
return Uint8Array.from(atob(base64), c => c.charCodeAt(0));
}
- 小程序中不支持
TextDecoder
js
function decrypt(key, info) {
// ·········
// ·········
// 5. 转 UTF-8 字符串
const decoder = new TextDecoder("utf-8");
// ·········
// ·········
}
处理
- 小程序中不支持
atob,替换方法
javascript
function base64ToBytes(base64) {
const arrayBuffer = uni.base64ToArrayBuffer(base64);
return new Uint8Array(arrayBuffer);
}
- 小程序中不支持
TextDecoder, 替换方法
ini
// Uint8Array 转 UTF-8 字符串
function utf8BytesToString(bytes) {
let str = '';
let i = 0;
while (i < bytes.length) {
const b1 = bytes[i++];
if (b1 < 0x80) {
str += String.fromCharCode(b1);
} else if (b1 < 0xE0) {
const b2 = bytes[i++];
str += String.fromCharCode(((b1 & 0x1F) << 6) | (b2 & 0x3F));
} else if (b1 < 0xF0) {
const b2 = bytes[i++];
const b3 = bytes[i++];
str += String.fromCharCode(
((b1 & 0x0F) << 12) |
((b2 & 0x3F) << 6) |
(b3 & 0x3F)
);
} else {
const b2 = bytes[i++];
const b3 = bytes[i++];
const b4 = bytes[i++];
let codepoint =
((b1 & 0x07) << 18) |
((b2 & 0x3F) << 12) |
((b3 & 0x3F) << 6) |
(b4 & 0x3F);
codepoint -= 0x10000;
str += String.fromCharCode(
0xD800 + (codepoint >> 10),
0xDC00 + (codepoint & 0x3FF)
);
}
}
return str;
}