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

Java中SecretKeySpec实现AES密钥生成的C#等价代码咨询

C# 等价实现代码

using System;
using System.Security.Cryptography;

public static class AesKeyHelper
{
    /// <summary>
    /// 从Base64编码字符串生成AES密钥,强制要求密钥长度为32字节(对应AES-256)
    /// </summary>
    /// <param name="secretKey">Base64编码的原始密钥字符串</param>
    /// <returns>可直接用于AES加解密的密钥字节数组</returns>
    /// <exception cref="ArgumentException">密钥长度不符合要求时抛出异常</exception>
    public static byte[] GetSecretKey(string secretKey)
    {
        byte[] decodeSecretKey = Base64Decode(secretKey);
        if (decodeSecretKey.Length != 32)
        {
            throw new ArgumentException("AES密钥长度必须为32字节", nameof(secretKey));
        }
        return decodeSecretKey;
    }

    /// <summary>
    /// Base64字符串解码
    /// </summary>
    public static byte[] Base64Decode(string data)
    {
        return Convert.FromBase64String(data);
    }

    // 可选:如果需要直接得到初始化好的AES算法实例,可以使用以下方法
    public static Aes CreateAesInstance(string base64SecretKey)
    {
        Aes aes = Aes.Create();
        aes.Key = GetSecretKey(base64SecretKey);
        // 可根据实际需求配置加密模式、填充模式、IV向量,需和Java端参数保持一致才能互通
        // 示例配置:aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7;
        return aes;
    }
}

说明

C# 没有和Java SecretKeySpec 完全对等的类,AES算法实例可直接接收字节数组格式的密钥,上述实现和原Java代码逻辑完全一致,同时补充了32字节长度校验符合需求。
如果需要和Java端加解密互通,请确保两边的加密模式、填充方式、IV向量三个参数完全一致。

内容的提问来源于stack exchange,提问作者Abishek G Chhetri

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 02:54:09