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;
}
相关推荐
程序员黑豆6 小时前
Java类型推断完全指南:从var到菱形运算符,掌握使用限制与最佳实践
java·前端·ai编程
To_OC6 小时前
踩了个 TS 的坑之后,我终于把 type 和 interface 掰明白了
前端·react.js·typescript
GreenTea6 小时前
深度解读 Anthropic 多智能体报告:更强的模型 ≠ 更好的协调
前端·后端·算法
浮生望7 小时前
前端API工程化:用 Mock 数据与 Axios 配置实现独立于后端的并行开发
前端
万少7 小时前
给 DeepSeek Harness 装个"应用商店":一条命令,595 个插件随你逛
前端·javascript·后端
波波0077 小时前
C# 15 重磅新特性: 带标签 break 与 continue:重新定义嵌套循环控制流
服务器·前端·c#
Brown.alexis8 小时前
es6知识点1-自备使用
前端·ecmascript·es6
小爬的老粉丝9 小时前
JavaScript 纯前端预览 WPS:先识别容器,再路由解析器
前端·javascript·wps
计算机魔术师9 小时前
新兴多智能体系统的模式与问题
前端
用户0595401744610 小时前
AI Agent 上下文污染踩坑实录:用 pytest + Redis 揪出 3 类记忆串号 bug,排查 6 小时
前端·css