You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用NodeJS Crypto解密AES加密字符串时出现错误

解决AES-128-ECB解密时的「wrong final block length」错误

这个错误的核心原因是解密时传入的字节流长度不是AES块大小(16字节)的整数倍,常见于base64解码异常、加密内容被篡改或加密/解密参数不匹配。针对你的代码,可按以下步骤修正:

修正加密/解密函数

确保加密和解密的参数完全对齐,显式指定编码避免隐式转换问题:

加密函数

const Crypto = require('crypto');

function encrypt(stringToEncrypt) {
  const key = '3f29658160528447';
  // 显式将key转为utf8编码的16字节Buffer(AES-128要求密钥长度16字节)
  const cipher = Crypto.createCipheriv('aes-128-ecb', Buffer.from(key, 'utf8'), null);
  // 指定输入字符串编码为utf8,避免默认转换异常
  const encryptedBuffer = Buffer.concat([
    cipher.update(stringToEncrypt, 'utf8'),
    cipher.final()
  ]);
  return encryptedBuffer.toString('base64');
}

解密函数

const Crypto = require('crypto');

function decrypt(encryptedText) {
  const key = '3f29658160528447';
  const decipher = Crypto.createDecipheriv('aes-128-ecb', Buffer.from(key, 'utf8'), null);
  // 确保从base64解码,指定输入编码
  const decryptedBuffer = Buffer.concat([
    decipher.update(encryptedText, 'base64'),
    decipher.final()
  ]);
  return decryptedBuffer.toString('utf8');
}

额外排查点

  • 如果encryptedText来自URL参数或外部存储,先做URL解码:比如将%2B还原为+,%2F还原为/,否则base64解码会得到错误的字节流
  • 确认加密后的base64字符串没有被截断、添加额外字符(比如换行、空格)
  • 验证stringToEncrypt是合法的UTF-8字符串,避免包含无法编码的二进制内容(如果需要加密二进制,要调整输入输出的编码方式)

内容的提问来源于stack exchange,提问作者Sh4dy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 08:01:21