使用 AES256 C# 解密字节数组时出错

Error while decrypting a bytes array using AES256 C#

我在另一台计算机上做一个加密私人文件的程序,同样的公式工作正常,我不明白为什么这部分代码不起作用,即使它以前工作过:

public static byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes)
{
    byte[] decryptedBytes = null;

    byte[] saltBytes = new byte[] { 2, 0, 0, 4, 0, 3, 0, 3 };

    using (MemoryStream ms = new MemoryStream())
    {
        using (RijndaelManaged AES = new RijndaelManaged())
        {
            AES.KeySize = 256;
            AES.BlockSize = 256;
            AES.Padding = PaddingMode.PKCS7;
            var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
            AES.Key = key.GetBytes(AES.KeySize / 8);
            AES.IV = key.GetBytes(AES.BlockSize / 8);

            AES.Mode = CipherMode.CFB;

            using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
            {
                cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
                cs.Close();
            }

            decryptedBytes = ms.ToArray();
        }
    }

    return decryptedBytes;
}

我已经尝试了大约 2 个小时,因为它在解密时给我这个错误,但依靠我所掌握的一点点加密知识是绝对不可能的。

首先,当我说 ChunkSize 时,我指的是 ChunkSize,因为首先我将文件拆分为 5Mb 字节数组,然后我加密或解密字节数组并将数据写入文件。 问题是,ChunkSize 小于 1Mb,这就是出现 CryptographicException 的原因。


                if (File.Exists(FileToDecrypt)) {
                    byte[] PasswordBytes;
                    if (IsFileTypePassword) {
                        PasswordBytes = File.ReadAllBytes(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),"K3ys\" + PasswordToDecrypt));
                    } else {
                        PasswordBytes = Encoding.UTF8.GetBytes(PasswordToDecrypt);
                    }
                    DecryptFile(5000000, FileToDecrypt, PasswordBytes); // Here was the problem
                    DecThread.Abort();
                }

这里是分割文件的函数,它和我的有点不同,但它做的是一样的,这段代码也是从另一个问题表单 Whosebug 中抓取的。

public static void SplitFile(string inputFile, int chunkSize, string path)
{
    byte[] buffer = new byte[chunkSize];

    using (Stream input = File.OpenRead(inputFile))
    {
        int index = 0;
        while (input.Position < input.Length)
        {
            using (Stream output = File.Create(path + "\" + index))
            {
                int chunkBytesRead = 0;
                while (chunkBytesRead < chunkSize)
                {
                    int bytesRead = input.Read(buffer, 
                                               chunkBytesRead, 
                                               chunkSize - chunkBytesRead);

                    if (bytesRead == 0)
                    {
                        break;
                    }
                    chunkBytesRead += bytesRead;
                }
                output.Write(buffer, 0, chunkBytesRead);
            }
            index++;
        }
    }
}