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

。_饼干妹妹 提交于 2021-02-16 17:55:14

问题


I am trying to perform AES 256-bit CBC encryption in C#. I am using the sample key/iv strings from this page: http://pic.dhe.ibm.com/infocenter/initiate/v9r5/topic/com.ibm.einstall.doc/topics/t_einstall_GenerateAESkey.html

However when I run the function below, I receive an error saying "Specified key is not a valid size for this algorithm." when attempting to set cipher.Key. I am able to use this key/iv combination in a node.js project, but I am attempting to port it to C# to no avail. What am I doing wrong below?

    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();
    }

回答1:


That key string is 64 characters long which is 512 bits, not 256. It looks like the string contains 32 hexadecimal values but then you need to do this instead:

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



回答2:


AES provides below bits based on secret key size.

16 length key size then AES-128 bit will be applicable. 24 length key size then AES-192 bit will be applicable. 32 length key size then AES-256 will be applicable.

Key sizes: 128, 192 or 256 bits Rounds: 10, 12 or 14 (depending on key size)



来源:https://stackoverflow.com/questions/26389309/issue-with-aes-256-bit-encryption-key-size-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!