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

CryptoJS与C# AES256加密输出不一致问题求助

AES 256加密:C#与CryptoJS结果不一致的问题排查

问题概述

两边输入均为字符串'675675',C#代码输出为yzFi7xGovxl0qcLsMoXZ9Q==,但CryptoJS代码输出为zJtuaFJcJdeSfZxneb6bTYDPjoH3QAz87HTaaLyn5Zc=,结果不匹配。

C# 参考代码

using System;
using System.Security.Cryptography;
using System.Text;

namespace Whatever.Class
{
    public class Program 
    {
        public static void Main(string[] args)
        {
            string moo = Encrypt_AES256.Encrypt256("675675", "5TGB&BJD!(JM(IK<5TGB&YHN7UJM(IK<", "!QAYDF7N#EDC4RFV");
            Console.WriteLine(moo);
        }
    }
    public class Encrypt_AES256
    {
        public static string Encrypt256(string text, string AesKey256, string AesIV256)
        {
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
            aes.BlockSize = 128;
            aes.KeySize = 256;
            aes.IV = Encoding.UTF8.GetBytes(AesIV256);
            aes.Key = Encoding.UTF8.GetBytes(AesKey256);
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;

            byte[] src = Encoding.Unicode.GetBytes(text);

            using (ICryptoTransform encrypt = aes.CreateEncryptor())
            {
                byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);
                return Convert.ToBase64String(dest);
            }
        }
    }
}

问题根源

1. 明文编码不匹配

C#中使用Encoding.Unicode.GetBytes(text)将明文转换为字节数组,Encoding.Unicode对应的是UTF-16LE编码(每个字符占2字节,小端序);而你的CryptoJS代码直接用WordArray.create(message)处理字符串,默认按UTF-8编码转换,这是结果差异的核心原因。

2. 密钥/IV的创建方式需明确编码

虽然CryptoJS的WordArray.create(string)默认按UTF-8解析,但显式使用CryptoJS.enc.Utf8.parse能更明确地对齐C#中Encoding.UTF8.GetBytes的逻辑,避免隐式转换问题。

修正后的CryptoJS代码

const encryptWithAES = message => {
    // 将明文转换为UTF-16LE字节数组,再转成WordArray(对应C#的Encoding.Unicode)
    const utf16leBytes = [];
    for (let i = 0; i < message.length; i++) {
        const charCode = message.charCodeAt(i);
        // UTF-16LE是小端序,先存低字节,再存高字节
        utf16leBytes.push(charCode & 0xFF);
        utf16leBytes.push((charCode >> 8) & 0xFF);
    }
    const plainWordArray = CryptoJS.lib.WordArray.create(utf16leBytes);

    // 密钥和IV按UTF-8编码转成WordArray(和C#的Encoding.UTF8.GetBytes一致)
    const key = CryptoJS.enc.Utf8.parse('5TGB&BJD!(JM(IK<5TGB&YHN7UJM(IK<');
    const iv = CryptoJS.enc.Utf8.parse('!QAYDF7N#EDC4RFV');

    const cipher = CryptoJS.AES.encrypt(plainWordArray, key, {
        iv: iv,
        padding: CryptoJS.pad.Pkcs7,
        mode: CryptoJS.mode.CBC,
    });

    return cipher.toString();
}

console.log(encryptWithAES('675675')); // 输出:yzFi7xGovxl0qcLsMoXZ9Q==

验证说明

修正后的代码会输出和C#完全一致的结果,核心是对齐了明文的UTF-16LE编码,同时确保密钥和IV的UTF-8编码逻辑与C#完全匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 20:25:30