使用 RijndaelManaged 类时,指定的初始化向量 (IV) 与此算法的块大小不匹配

问题描述

我正在使用 RijndaelManaged 类在 C# 中使用 AES 加密字符串,但出现错误

Specified initialization vector (IV) does not match the block size for this algorithm.

加密字符串的方法如下:

    public static byte[] AEsstringEncryption(string plainText,string stringMasterSecret,string hashedContent)
    {
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText");
       
        byte[] encrypted;
        byte[] concatenated;
        using (RijndaelManaged AES = new RijndaelManaged())
        {
            AES.KeySize = 256;
            AES.BlockSize = 128;
            AES.Padding = PaddingMode.PKCS7;

            byte[] salt = Encryption.generaterandom();
            string testPassword = Encryption.RandomString(32,true);

            var algorithm = HashAlgorithmName.SHA256;
            byte[] masterSecret = Encoding.UTF8.GetBytes(stringMasterSecret);
            byte[] info = Encoding.UTF8.GetBytes(hashedContent);
           
            var hkdf = new HKDF(algorithm,masterSecret,info,32,salt);
            byte[] hash = hkdf.hash;

            RC2CryptoServiceProvider rc2sp = new RC2CryptoServiceProvider();
            byte[] key = hkdf.hash;
            byte[] IV = rc2sp.IV;
            AES.Key = key;
            AES.IV = IV;

            ICryptoTransform encryptor = AES.CreateEncryptor(AES.Key,AES.IV);

            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt,encryptor,CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                    concatenated = new byte[IV.Length + encrypted.Length];
                    System.Buffer.Blockcopy(IV,concatenated,IV.Length);
                    System.Buffer.Blockcopy(encrypted,IV.Length,encrypted.Length);
                }
            }
        }
        return concatenated;
    }

你能帮我找出错误的来源吗?谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)