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

Node.js中AES-256(ECB/PKCS5Padding)密钥生成及加密问题求助

认证请求404问题排查与AES/RSA加密修正方案

问题背景

需要按以下流程生成认证请求,当前实现返回404错误,怀疑AES密钥生成或加密步骤存在问题:

  1. 用AES-256(AES/ECB/PKCS5Padding)生成随机密钥并转Base64字符串
  2. 构造包含username、password、encryptKey、refreshToken的JSON对象
  3. 用MAURA的RSA公钥加密该JSON字符串,转Base64后封装为指定请求格式发送

现有Node.js代码如下:

// import the path module
const path = require('node:path');
const crypto = require('crypto');

// get the public key certificate
const CRTpath = path.basename('./PublicKey.crt');

const GenKey = crypto.randomBytes(32);

// encode key to Base 64
const base64Key = Buffer.from(GenKey).toString('base64');

const OBJ = {
username: "xxx",
password: "xasadsd",
encryptKey: base64Key,
refreshToken: "false"
}

let jsonOBJ = JSON.stringify(OBJ);

function encryptString (plaintext, publicKeyFile) {
const publicKey = fs.readFileSync(publicKeyFile, "utf8");

    // publicEncrypt() method with its parameters 
    const encrypted = crypto.publicEncrypt( 
             publicKey, Buffer.from(plaintext)); 
    return encrypted; 

}

const encrypted = encryptString(jsonOBJ, CRTpath);

const baseEncrypted = Buffer.from(encrypted, 'utf8').toString("base64");

指定请求格式:

{
  "requestID": "string",
  "payload": "" // 填入上述加密后的Base64字符串
}

代码问题分析

  1. 未引入fs模块,导致fs.readFileSync无法执行
  2. path.basename('./PublicKey.crt')仅返回文件名,无法正确定位证书文件路径
  3. RSA加密返回的encrypted是Buffer类型,用Buffer.from(encrypted, 'utf8')二次转换会破坏二进制数据
  4. 未指定RSA加密的填充模式,部分服务端会要求明确匹配的填充规则

修正后的完整代码

const path = require('node:path');
const crypto = require('crypto');
const fs = require('fs'); // 补充引入文件系统模块

// 获取证书完整路径,避免相对路径读取失败
const CRTpath = path.resolve('./PublicKey.crt');

// 生成AES-256随机密钥(32字节)并转Base64
const genKey = crypto.randomBytes(32);
const base64Key = genKey.toString('base64'); // 直接调用Buffer的toString方法更简洁

const authObj = {
  username: "xxx",
  password: "xasadsd",
  encryptKey: base64Key,
  refreshToken: "false"
};

const jsonStr = JSON.stringify(authObj);

function encryptWithRSA(plaintext, publicKeyPath) {
  try {
    const publicKey = fs.readFileSync(publicKeyPath, 'utf8');
    // 明确指定RSA填充模式和哈希算法,匹配服务端要求
    const encrypted = crypto.publicEncrypt(
      {
        key: publicKey,
        padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, // 若服务端用旧版则改为RSA_PKCS1_PADDING
        oaepHash: 'sha256' // 部分服务端要求sha256,默认sha1可能不兼容
      },
      Buffer.from(plaintext)
    );
    return encrypted.toString('base64'); // 直接将二进制加密结果转Base64
  } catch (err) {
    console.error('加密失败:', err);
    throw err;
  }
}

const encryptedPayload = encryptWithRSA(jsonStr, CRTpath);

// 构造最终请求体
const requestBody = {
  requestID: "your-unique-request-id",
  payload: encryptedPayload
};

// 示例:发送请求(需自行引入axios等HTTP库)
// const axios = require('axios');
// axios.post('your-authentication-api-url', requestBody)
//   .then(res => console.log('认证成功:', res.data))
//   .catch(err => console.error('请求失败:', err));

关键注意事项

  • AES密钥生成:crypto.randomBytes(32)生成的32字节随机数完全符合AES-256的密钥要求,直接转Base64即可
  • 证书路径:使用path.resolve获取完整文件路径,避免因工作目录变化导致的证书读取失败
  • RSA加密参数:必须和服务端保持一致,若不确定填充模式,可先尝试RSA_PKCS1_PADDING(旧版常用)和RSA_PKCS1_OAEP_PADDING(新版标准)
  • 404错误排查:若加密逻辑修正后仍返回404,需优先确认请求URL是否正确、服务端是否存在对应接口,排除路由配置问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 03:57:24