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

使用Node.js crypto模块时出现Unknown cipher错误求助

问题:使用cipher进行AES-256加密时抛出Unknown cipher错误,代码存在什么问题?

原代码

function paymenIdEncryption(specialtyID,paymentId) {
    const convertToString = `${paymentId}_${specialtyID}`;
    const secret_key = "EiE0BVQle0xFjZvYOupKjHJKAcAwBaTjlZ7G7rryNos=";
    const iv = crypto.randomBytes(16);

    const cipher = crypto.createCipheriv('aes-256-cbs', Buffer.from(secret_key, 'base64'), iv);
    let encrypted = cipher.update(Buffer.from(convertToString, 'utf-8'));
    encrypted = Buffer.concat([encrypted, cipher.final()]);

    const encryptedData = {
        iv: iv.toString('base64'),
        encrypted: encodeURIComponent(encrypted),
    }

    return encryptedData;;
}

console.log(paymenIdEncryption(13780298 ,"8018928"))

错误信息

Error: Unknown cipher
    at Cipheriv.createCipherBase (node:internal/crypto/cipher:116:19)
    at Cipheriv.createCipherWithIV (node:internal/crypto/cipher:135:3)
    at new Cipheriv (node:internal/crypto/cipher:243:3)
    at Object.createCipheriv (node:crypto:138:10)

问题解决

核心错误:加密模式拼写错误

你写的'aes-256-cbs'是不存在的加密模式,正确的CBC模式拼写为'aes-256-cbc'(CBC是Cipher Block Chaining的缩写,是AES标准支持的分组加密模式),这是触发"Unknown cipher"错误的直接原因。

其他需修正的细节

  1. 缺少crypto模块引入:原代码未导入Node.js的crypto模块,运行时会报错crypto is not defined,需在代码开头添加const crypto = require('crypto');。
  2. 函数名拼写错误:paymenIdEncryption少了一个t,修正为paymentIdEncryption,规范命名便于后续维护。
  3. 多余分号:返回语句return encryptedData;;多了一个分号,可直接删除。
  4. 加密结果编码优化:encodeURIComponent(encrypted)会将Buffer转为UTF-8字符串再编码,可能出现乱码问题,建议改用encrypted.toString('base64'),和IV的编码方式统一,后续解密更便捷。

修正后的完整代码

const crypto = require('crypto');

function paymentIdEncryption(specialtyID, paymentId) {
    const convertToString = `${paymentId}_${specialtyID}`;
    const secret_key = "EiE0BVQle0xFjZvYOupKjHJKAcAwBaTjlZ7G7rryNos=";
    const iv = crypto.randomBytes(16);

    // 修正加密模式为aes-256-cbc
    const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(secret_key, 'base64'), iv);
    let encrypted = cipher.update(Buffer.from(convertToString, 'utf-8'));
    encrypted = Buffer.concat([encrypted, cipher.final()]);

    const encryptedData = {
        iv: iv.toString('base64'),
        encrypted: encrypted.toString('base64'),
    }

    return encryptedData;
}

console.log(paymentIdEncryption(13780298, "8018928"));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 07:55:24