首页 > 解决方案 > PHP openssl_encrypt 响应与 CryptoJS AES 加密不匹配

问题描述

PHP 加密逻辑

$secret_key = '###$$**@@@//!!!^^%%%';
$secret_iv = '$$##!!&&**!!**@@';

$encrypt_method = "AES-256-CBC";
$key = hash('sha256', $secret_key); // d7cc77e5a8db446cc11aaa510b5191852a0084ad09f7b33623137c78e09c8050
$iv = substr(hash('sha256', $secret_iv), 0, 16); // 36a50210c8b2f19e

$output = openssl_encrypt('testingDemo', $encrypt_method, $key, 0, $iv);
// response --> uRfctdzWekUYISdKHKW88Q==

JS 加密逻辑

const SECRET_KEY = '###$$**@@@//!!!^^%%%';
const SECRET_IV = '$$##!!&&**!!**@@';
const key = SHA256(SECRET_KEY); // d7cc77e5a8db446cc11aaa510b5191852a0084ad09f7b33623137c78e09c8050
const iv = SHA256(SECRET_IV).toString().substr(0, 16); // 36a50210c8b2f19e
console.log(iv, 'iv....');
const encrypted = AES.encrypt('testingDemo', key, { iv: enc.Hex.parse(iv) });
console.log(encrypted.toString(enc.Base64) // response --> vXyYVoSYagBbN0ihXVTgaA==

我不知道我做错了什么。请有人帮忙。

==============================
更新。工作守则

JS 加密逻辑

export const tokenGenerator = (subdomain) => {
  const plainText = `${atob(process.env.REACT_APP_PREFIX)}${subdomain}${atob(process.env.REACT_APP_SUFFIX)}`;
  const key = SHA256(atob(process.env.REACT_APP_SECRET_KEY)).toString().substr(0, 32);
  const iv = SHA256(atob(process.env.REACT_APP_SECRET_IV)).toString().substr(0, 16);
  const encrypted = AES.encrypt(plainText, enc.Utf8.parse(key), { iv: enc.Utf8.parse(iv) });
  return btoa(enc.Base64.stringify(encrypted.ciphertext));
};

PHP 加密逻辑

$secret_key = '###$$**@@@//!!!^^%%%';
$secret_iv = '$$##!!&&**!!**@@';
$encrypt_method = "AES-256-CBC";
$key = hash('sha256', $secret_key);
$iv = substr(hash('sha256', $secret_iv), 0, 16);
$output = openssl_encrypt('testingDemo', $encrypt_method, $key, 0, $iv);

标签: javascriptphpencryptioncryptojs

解决方案


推荐阅读