【问题标题】:Issue with AES 256-Bit Encryption Key Size in C#C# 中 AES 256 位加密密钥大小的问题
【发布时间】:2014-10-15 18:13:05
【问题描述】:

我正在尝试在 C# 中执行 AES 256 位 CBC 加密。我正在使用此页面中的示例键/iv 字符串:http://pic.dhe.ibm.com/infocenter/initiate/v9r5/topic/com.ibm.einstall.doc/topics/t_einstall_GenerateAESkey.html

但是,当我运行下面的函数时,我收到一条错误消息,提示“指定的密钥不是此算法的有效大小”。尝试设置 cipher.Key 时。我可以在 node.js 项目中使用此键/iv 组合,但我试图将其移植到 C# 无济于事。我在下面做错了什么?

    static void Main(string[] args)
    {
        string keyString = "B374A26A71490437AA024E4FADD5B497FDFF1A8EA6FF12F6FB65AF2720B59CCF";
        string ivString = "7E892875A52C59A3B588306B13C31FBD";

        byte[] key = Encoding.UTF8.GetBytes(keyString);
        byte[] iv = Encoding.UTF8.GetBytes(ivString);

        Console.WriteLine("Key is " + key.Length + " bytes.");

        using (RijndaelManaged cipher = new RijndaelManaged())
        {
            cipher.Mode = CipherMode.CBC;
            cipher.KeySize = 256;
            cipher.BlockSize = 128;
            cipher.Key = key;
            cipher.IV = iv;

            // Create a decrytor to perform the stream transform.
            ICryptoTransform encryptor = cipher.CreateEncryptor(cipher.Key, cipher.IV);
        }

        Console.WriteLine("Success!");
        Console.ReadKey();
    }

【问题讨论】:

    标签: c# encryption aes


    【解决方案1】:

    该密钥字符串长 64 个字符,即 512 位,而不是 256 位。看起来该字符串包含 32 个十六进制值,但您需要改为:

    byte[] key = new byte[] { 0xB3, 0x74, 0xA2, 0x6A, 0x71, 0x49, 0x04 etc. };
    

    【讨论】:

    • 啊,非常感谢!它确实包含 32 个十六进制值,所以我只需将字符串转换为十六进制(使用此解决方案 stackoverflow.com/questions/321370/…)然后检索字节。
    【解决方案2】:

    AES 根据密钥大小提供以下位。

    16 长度密钥大小,然后 AES-128 位将适用。 24 长度密钥大小,然后 AES-192 位将适用。 32 长度的密钥大小,然后 AES-256 将适用。

    密钥大小:128、192 或 256 位 轮数:10、12 或 14(取决于密钥大小)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-16
      • 1970-01-01
      • 1970-01-01
      • 2020-07-26
      • 2021-04-22
      • 1970-01-01
      • 2017-06-07
      相关资源
      最近更新 更多