使用aes的视频加密
本文关键字:加密 的视频 aes 使用 | 更新日期: 2023-09-27 18:24:57
此代码适用于较小的文件,即使是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;
}
我在这里做错了什么?
您的问题很可能是您将其作为x86运行,并填满了进程可用的RAM。这样做可以将体系结构更改为x64,因此您的唯一限制是系统中的RAM数量:
- 单击"生成"
- 选择"Configuration Manager"
- 在"平台"下,单击"新建"
- 选择x64作为新平台
- 保留默认的"复制设置自"(任何CPU)
- 单击"确定"
- 为解决方案中的每个项目选择x64
如果问题仍然存在,那么您将不得不将文件拆分为更小的数组,并分别处理它们。
代码示例,演示如何拆分文件。警告:这是一个例子,它没有完全优化:
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...
}