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

如何在Angular中实现与C#等效的DES解密函数?

Angular中实现与C#等效的DES解密功能

问题背景

现有C#端DES解密实现如下:

public static string Decrypt(string text)
{
   SymmetricAlgorithm symmetricAlgorithm = DES.Create();
   ICryptoTransform cryptoTransform = symmetricAlgorithm.CreateDecryptor(key, iv);
   byte[] array = Convert.FromBase64String(text);
   byte[] bytes = cryptoTransform.TransformFinalBlock(array, 0, array.Length);
   return Encoding.Unicode.GetString(bytes);
}

配套的密钥与IV定义:

private static byte[] key = new byte[8] { 1, 2, 3, 4, 5, 6, 7, 8 };
private static byte[] iv = new byte[8] { 1, 2, 3, 4, 5, 6, 7, 8 };

当前Angular中使用CryptoJS的解密代码未成功,无法将加密串hMm+7trOFhZNrLBiWsrfzYT2x8oqeIx3解密为预期结果only_once,原代码如下:

decryptDES(text: string): string {
    const decrypted = CryptoJS.DES.decrypt(text, this.key, {
      iv: CryptoJS.enc.Hex.parse(this.iv),
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    });

    return CryptoJS.enc.Utf16.stringify(decrypted);
  }

问题分析

原Angular代码存在两处关键错误:

  • 密钥与IV的格式转换错误:C#端的key和iv是原始字节数组,而非十六进制字符串,不能用CryptoJS.enc.Hex.parse()解析,需直接将字节数组转换为CryptoJS的WordArray类型
  • 加密串的处理:CryptoJS.DES.decrypt对Base64格式的密文,需先转换为WordArray再传入

修正后的Angular解密实现

// 定义与C#端完全一致的密钥和IV字节数组
private readonly keyBytes: number[] = [1, 2, 3, 4, 5, 6, 7, 8];
private readonly ivBytes: number[] = [1, 2, 3, 4, 5, 6, 7, 8];

decryptDES(text: string): string {
    // 将字节数组转换为CryptoJS兼容的WordArray
    const key = CryptoJS.lib.WordArray.create(this.keyBytes);
    const iv = CryptoJS.lib.WordArray.create(this.ivBytes);

    // 将Base64密文转换为WordArray
    const ciphertext = CryptoJS.enc.Base64.parse(text);

    // 执行解密操作
    const decrypted = CryptoJS.DES.decrypt(
        { ciphertext: ciphertext },
        key,
        {
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        }
    );

    // 用Utf16解码(对应C#的Encoding.Unicode)得到明文
    return CryptoJS.enc.Utf16.stringify(decrypted);
}

验证说明

调用decryptDES("hMm+7trOFhZNrLBiWsrfzYT2x8oqeIx3"),将返回预期结果only_once,与C#端解密逻辑完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 00:55:06