Karsten
Karsten

Reputation: 83

Decryption of large file with AES

I'm trying to decrypt 500 mb of data, and im getting a out of memory exception on larger files, so the decryption works for smaller sized files, is there anyway I can ensure that I'm not getting this out of memory exception?

The first part of the key.file is the IV and the second part of the key.file is the key.

My machine got 32 gb of memory, so it's not a local problem.

The code breaks on this line: var so = decrTransform.TransformFinalBlock(file, 0, file.Length);

private void DecryptData() {

        X509Certificate2 cert;

        var storeLocation = (StoreLocation)Enum.Parse(typeof(StoreLocation), "LocalMachine", true);
        var storeName = (StoreName)Enum.Parse(typeof(StoreName), "My", true);
        var findType = (X509FindType)Enum.Parse(typeof(X509FindType), "FindByThumbprint", true);
        string thumbprint = Thumb;

        try
        {
            X509Store certStore = new X509Store(storeName, storeLocation);
            certStore.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection certCollection = certStore.Certificates.Find(findType,
                thumbprint, false);
            certStore.Close();
            cert = new X509Certificate2(certCollection[0]);
        }
        catch (Exception ex)
        {
            throw ex;
        }

        RijndaelManaged alg = new RijndaelManaged();

        try
        {
            var asd = ((RSACryptoServiceProvider)cert.PrivateKey).Decrypt("file.key.path"), true);

            var iv = new byte[16];
            Buffer.BlockCopy(asd, 0, iv, 0, 16);

            var key = new byte[32];
            Buffer.BlockCopy(asd, 16, key, 0, 32);
            alg.Padding = PaddingMode.PKCS7;
            alg.Mode = CipherMode.CBC;



            using (ICryptoTransform decrTransform = alg.CreateDecryptor(key, iv))
            {
                byte[] file = ReadFile(@"encrypted.file.path");


                    var so = decrTransform.TransformFinalBlock(file, 0, file.Length);
                    File.WriteAllBytes(@"SavedData.path", so);




                decrTransform.Dispose();
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

Upvotes: 1

Views: 930

Answers (1)

Maarten Bodewes
Maarten Bodewes

Reputation: 93968

Try using streams, especially CryptoStream. The Microsoft example at the bottom of this page actually perform file based encryption with RijndaelManaged so you're in luck. You would first need to extract the IV from the file stream of course, e.g. by reading exactly 16 bytes byte-by-byte. Only wrap the stream after reading the IV.

That way there is no need for memory consumption other than a buffer size, which should range in a few KiB maximum.

Upvotes: 2

Related Questions