簡體   English   中英

C# 中 AES 256 位加密密鑰大小的問題

[英]Issue with AES 256-Bit Encryption Key Size in C#

我正在嘗試在 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 項目中使用這個 key/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();
    }

該密鑰字符串有 64 個字符長,即 512 位,而不是 256 位。看起來該字符串包含 32 個十六進制值,但您需要這樣做:

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

AES 根據密鑰大小提供以下位。

16 個長度的密鑰大小,那么 AES-128 位將適用。 24 個長度的密鑰大小,那么 AES-192 位將適用。 32 長度的密鑰大小,則 AES-256 將適用。

密鑰大小:128、192 或 256 位輪次:10、12 或 14(取決於密鑰大小)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM