2016-04-28 77 views
1

我試圖解密500MB的數據,並且即時解決大文件內存異常問題,所以解密適用於較小文件,無論如何我都可以確保我能夠解密大文件,米沒有得到這種內存不足的例外?用AES解密大文件

key.file的第一部分是第四部分,key.file的第二部分是關鍵。

我的機器有32GB的內存,所以它不是本地問題。

代碼在此行中斷:var so = decrTransform.TransformFinalBlock(file,0,file.Length);

私人無效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; 
     } 
    } 
+0

32位操作系統或64位操作系統?編譯爲32位.NET或64位.NET? – davidbak

+0

整個512MB是在一個進程中加密的嗎? –

+0

事情是,一個32位.NET進程只能訪問2GB(用戶區域),並且可能無法分配大塊連續內存。您已經爲您讀入的文件找到了一個〜500Mb的連續內存塊。您的進程地址空間中可能沒有第二個〜500Mb連續內存塊用於解碼數據。如果你正在運行32位。 – davidbak

回答

2

嘗試使用流,尤其是CryptoStreamMicrosoft example at the bottom of this page實際上使用RijndaelManaged執行基於文件的加密,所以你很幸運。您首先需要從當然的文件流中提取IV,例如,通過讀取確切地說 16字節逐字節。只有在閱讀完IV後才能包裝流。

這樣就不需要除緩衝區大小之外的內存消耗,緩衝區大小的範圍應該在幾個KiB最大值範圍內。

+0

是的,你是對的,我試圖使用流而不是字節數組,現在它按預期工作 - 謝謝:) – Karsten