问题
This code works for smaller files even mp3 and around 50mb video files but it gives me error saying out of memory when it try to encrypt larger video files(>1gb) in c# win application
AES algorithm:
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;
}
What am I doing wrong here?
回答1:
Your problem is most likely that you are running this as x86 and fulling the RAM available for the process. Do this to change the architecture to x64 so your only limit is the amount of RAM in your system:
- Click on Build
- Select "Configuration Manager"
- Under Platform, click on New
- Select x64 as new platform
- Leave the default "copy settings from" (Any CPU)
- Click ok
- Choose x64 for every project in your solution
If the problem still happens, then you will have to split the file into smaller arrays and work with them separately.
Code example, to demonstrate how you could split the file. WARNING: This is an example, and it's not completely optimized:
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...
}
来源:https://stackoverflow.com/questions/33975143/video-encryption-using-aes