此代码适用于较小的文件,即使是mp3和大约50mb的视频文件,但是当它尝试在c#win应用程序中加密较大的视频文件(> 1gb)时,它会让我错误地说内存不足
AES算法:
public byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
{
byte[] encryptedBytes = null;
byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CBC;
using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
cs.Close();
}
encryptedBytes = ms.ToArray();
}
}
return encryptedBytes;
}
我在这里做错了什么?
答案 0 :(得分:1)
您的问题很可能就是将其作为x86运行并为该进程填充了可用的RAM。这样做是为了将体系结构更改为x64,因此您的唯一限制是系统中的RAM数量:
如果问题仍然存在,那么您必须将文件拆分为较小的数组并单独使用它们。
代码示例,演示如何拆分文件。警告:这是一个示例,并未完全优化:
FileInfo info = new FileInfo(@"D:\SomeMovie.avi");
int bytesToRead = 128 * 1024 * 1024; // 128MB
byte[] buffer = new byte[bytesToRead]; // create the array that will be used encrypted
long fileOffset = 0;
int read = 0;
bool allRead = false;
while (!allRead)
{
using (FileStream fs = new FileStream(info.FullName, FileMode.Open, FileAccess.Read))
{
fs.Seek(fileOffset, SeekOrigin.Begin); // continue reading from where we were...
read = fs.Read(buffer, 0, bytesToRead); // read the next chunk
}
if (read == 0)
allRead = true;
else
fileOffset += read;
// encrypt the stuff, do what you need...
}