AES-GCM 解密失败解决方案

背景

使用uniapp开发微信小程序,因为后端返回参数有加密数据使用的是AES_GCM加密算法,因此使用asmcrypto.js用于解密,微信开发者工具中,代码正常,但是部署上线后出现atobBufferTextDecoderundefind情况

问题代码

  • 小程序中不支持 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;
}
相关推荐
遇见~未来7 小时前
JavaScript数组全解析:从本质到高级技巧
开发语言·前端·javascript
石像鬼₧魂石7 小时前
80 端口(Web 服务)渗透测试完整总结(含踩坑 + 绕过 + 实战流程)
linux·运维·服务器·前端·网络·阿里云
C_心欲无痕8 小时前
nginx - 核心概念
运维·前端·nginx
开开心心_Every8 小时前
安卓做菜APP:家常菜谱详细步骤无广简洁
服务器·前端·python·学习·edge·django·powerpoint
前端_Danny8 小时前
用 ECharts markLine 实现节假日标注
前端·信息可视化·echarts
古城小栈8 小时前
Rust 丰富&好用的 格式化语法
前端·算法·rust
丢,捞仔8 小时前
uni-app上架应用添加权限提示框
前端·javascript·uni-app
Glink8 小时前
从零开始编写自己的AI账单Agent
前端·agent·ai编程
Hilaku8 小时前
我是如何用一行 JS 代码,让你的浏览器内存瞬间崩溃的?
前端·javascript·node.js
努力犯错玩AI8 小时前
如何在ComfyUI中使用Qwen-Image-Layered GGUF:完整安装和使用指南
前端·人工智能