video encryption using aes

依然范特西╮ 提交于 2019-12-12 05:27:40

问题


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:

  1. Click on Build
  2. Select "Configuration Manager"
  3. Under Platform, click on New
  4. Select x64 as new platform
  5. Leave the default "copy settings from" (Any CPU)
  6. Click ok
  7. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!