简体   繁体   English

C# 中 RijndaelManaged 的​​ IV 块大小问题

[英]IV Block Size Issue with RijndaelManaged in C#


I am having trouble with this code to encrypt a string using RinjndaelManaged.我在使用 RinjndaelManaged 加密字符串时遇到了此代码的问题。 I kept getting the error " Specified initialization vector (IV) does not match the block size for this algorithm " and have matched the key and IV length and tried a 32 char length for they key and every 4 bytes from 4 to 32. The code errors at the line starting with:我不断收到错误消息“指定的初始化向量 (IV) 与此算法的块大小不匹配”,并且匹配了密钥和 IV 长度,并尝试了 32 个字符长度的密钥和从 4 到 32 的每 4 个字节。代码以以下开头的行中的错误:

aes.IV = Convert.FromBase64String(myString);

The code block is as follows:代码块如下:

private String AES_encrypt(String Input)
    {
        var aes = new RijndaelManaged();
        aes.KeySize = 256;
        aes.BlockSize = 256;
        aes.Padding = PaddingMode.PKCS7;
        String myString = new string('J', 32);
        aes.Key = Convert.FromBase64String(myString);
        aes.IV = Convert.FromBase64String(myString);
        var encrypt = aes.CreateEncryptor(aes.Key, aes.IV);
        byte[] xBuff = null;
        using (var ms = new MemoryStream())
        {
            using (var cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write))
            {
                byte[] xXml = Encoding.UTF8.GetBytes(Input);
                cs.Write(xXml, 0, xXml.Length);
            }

            xBuff = ms.ToArray();
        }

        String Output = Convert.ToBase64String(xBuff);
        return Output;
    }
}

I only used the myString length to just to quickly iterate through a bunch of options.我只使用 myString 长度来快速迭代一堆选项。 I'm using this particular Keysize/Block/Padding and encryption scheme to work with PHP code which would decrypt this data.我正在使用这个特殊的 Keysize/Block/Padding 和加密方案来处理解密这些数据的 PHP 代码。

A string of 32 'J's will produce 24 bytes, not 16 or 32. Do not try to Base64 decode it.一个由 32 个 'J 组成的字符串将产生 24 个字节,而不是 16 或 32 个字节。不要尝试对它进行 Base64 解码。 Best to read-up on Base64.最好在 Base64 上阅读。

It is not secure to use the same value for the key and IV.对密钥和 IV 使用相同的值是不安全的。

The resulting Base64 string that you want to set as an IV is 16 bytes (128 bit) long, whereas your encryption algorithm requires a 256 bit IV.您想要设置为 IV 的结果 Base64 字符串的长度为 16 字节(128 位),而您的加密算法需要 256 位的 IV。

Change your IV to a byte array that is 32 bytes long.将您的 IV 更改为 32 字节长的字节数组。

Base64: 'JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ'

Decoded: '$I$I$I$I$I$I$I$I' (16 bytes = 128 bits long)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM