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

Node.js使用CryptoJS加密后解密为空的原因及解决方法

Why Your AES Decryption Returns Empty and How to Fix It

Let's break down the two critical issues in your code that are causing the empty decryption result:

1. You're Passing Raw Ciphertext Directly to CryptoJS.AES.decrypt

When encrypting, you extract just the ciphertext as a hex string (result.ciphertext.toString(CryptoJS.enc.Hex)). When decrypting, you parse this back to a WordArray—but CryptoJS.AES.decrypt doesn't recognize raw WordArrays as valid ciphertext input. It expects either:

  • A CipherParams object (which explicitly labels the ciphertext, IV, and other metadata), or
  • The full encoded string output from CryptoJS.AES.encrypt() (which bundles all necessary details)

Since you're working with raw ciphertext, you need to wrap your parsed WordArray in a CipherParams object with the ciphertext property set.

2. You're Not Converting the Decrypted Result to a UTF-8 String

The output of CryptoJS.AES.decrypt is a WordArray representing your original plaintext (which was encoded as UTF-8 by default during encryption). Calling .toString() without arguments returns the hex representation of this WordArray, not the actual string you want. You need to explicitly use CryptoJS.enc.Utf8 to get back your original plaintext.


Fixed DecryptHex Function

Here's the corrected version of your decryption function:

const DecryptHex = (string, chip, skey) => {
  let result = '';
  const key = CryptoJS.enc.Hex.parse(skey);
  const iv = CryptoJS.lib.WordArray.create([0x00, 0x00, 0x00, 0x00]);
  try {
    const array = CryptoJS.enc.Hex.parse(string);
    if (chip === 'AES') {
      // Wrap ciphertext in a CipherParams object and convert result to UTF-8
      result = CryptoJS.AES.decrypt(
        { ciphertext: array }, 
        key, 
        { iv: iv, mode: CryptoJS.mode.CBC }
      ).toString(CryptoJS.enc.Utf8);
      console.log('$$$$');
      console.log('result : ', result);
      console.log('$$$$');
    } else {
      result = array.toString(CryptoJS.enc.Hex); // Convert WordArray back to hex for non-AES cases
    }
    return result;
  } catch (error) {
    throw error;
  }
};

Additional Checks

  • Ensure your STORE_KEY is a valid hex string of the correct length for AES: 16 bytes (32 hex chars) for AES-128, 24 bytes (48 hex chars) for AES-192, or 32 bytes (64 hex chars) for AES-256. An invalid key length will silently break decryption.
  • Your IV is correctly set to 16 bytes (4 x 32-bit words of 0), which matches AES's block size—this part is configured properly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 17:22:42