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

AES-256-CBC加密:PHP转TypeScript/CryptoJS代码适配求助

匹配PHP AES-256-CBC逻辑的TypeScript/CryptoJS加密实现

问题背景

已有可正常运行的PHP AES-256-CBC加密代码,但自行编写的CryptoJS代码无法匹配其逻辑,需要编写一致的TypeScript/CryptoJS实现。

PHP工作代码

$firstName = "My Name";
$lastName = "Last name";
$email = "My email";

$data = http_build_query(array(
    "firstname" => $firstName,
    "lastname" => $lastName,
    "email" => $email,
    "username" => $email,
    "password" => ""
));

$key = 'MySecret Key goes here'; // 32位长度

// 生成16位长度的初始化向量
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));

// AES-256-CBC加密
$encrypted = openssl_encrypt($data, 'aes-256-cbc', $key, 0, $iv);

// 拼接密文与IV后Base64编码
$salt = base64_encode($encrypted . '::' . $iv);

echo $salt;

原CryptoJS代码的问题

  • 密钥解析错误:PHP直接使用32位字符串作为密钥,原代码错误用Hex.parse处理密钥(会把字符串当作十六进制解析,导致密钥完全不符)。
  • IV处理错误:PHP生成16字节随机二进制IV,原代码用无效十六进制字符串硬编码IV,未遵循随机生成逻辑。
  • 拼接逻辑错误:PHP将Base64密文与二进制IV拼接后再整体Base64编码,原代码直接拼接WordArray对象,未正确转换格式。

正确的TypeScript/CryptoJS实现

// 构造与PHP http_build_query一致的查询字符串
const buildQueryString = (params: Record<string, string>): string => {
  return new URLSearchParams(params).toString();
};

// 核心加密函数
const encryptData = (key: string) => {
  // 1. 构造待加密数据
  const params = {
    firstname: "My Name",
    lastname: "Last name",
    email: "My email",
    username: "My email",
    password: ""
  };
  const data = buildQueryString(params);

  // 2. 处理密钥:直接解析32位UTF-8字符串
  const cryptoKey = CryptoJS.enc.Utf8.parse(key);

  // 3. 生成16字节随机IV(与PHP openssl_random_pseudo_bytes一致)
  const iv = CryptoJS.lib.WordArray.random(16);

  // 4. AES-256-CBC加密,参数与PHP对齐
  const encrypted = CryptoJS.AES.encrypt(data, cryptoKey, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });

  // 5. 拼接密文(Base64格式)与原始二进制IV,再整体Base64编码
  const encryptedBase64 = encrypted.toString();
  const ivRaw = CryptoJS.enc.Latin1.stringify(iv); // 将IV转为二进制字符串
  const combined = encryptedBase64 + '::' + ivRaw;
  const salt = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(combined));

  return salt;
};

// 调用示例(替换为你的32位密钥)
const key = 'MySecret Key goes here'; // 确保长度为32位
const result = encryptData(key);
console.log(result);

关键说明

  • Query字符串构造:使用URLSearchParams模拟PHP的http_build_query,确保参数编码一致。
  • 密钥处理:直接用Utf8.parse解析32位密钥字符串,与PHP的密钥使用逻辑完全匹配。
  • IV生成:用WordArray.random(16)生成16字节随机IV,对应PHP的openssl_random_pseudo_bytes。
  • 拼接与编码:将加密后的Base64密文、原始二进制IV用::分隔后,整体进行Base64编码,完全复刻PHP的base64_encode($encrypted . '::' . $iv)逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 04:54:16