I try to read a file, separate the lines (each line represents different data), decrypt the symmetric key with my RSA private key, decrypt and verify the data using AES GCM, and write it to the same directory.
But after decrypting the data it looks like it still holds a lot of RAM.
I tried to use the .clear function, assigning the variable to null, and using the GC.Collect() function.
The GC.Collect() worked the best (reduced RAM usage from 6GB to 1.5GB when decrypting 700MB file).
Here is the the function that runs when I try to decrypt.
private void decrypt()
{
if (!decrypted)
{
try
{
string[] lines = File.ReadAllLines(openFileDialog1.FileName);
byte[] encryptedsk = Convert.FromBase64String(lines[0]);
byte[] nonce = Convert.FromBase64String(lines[1]);
byte[] tag = Convert.FromBase64String(lines[2]);
byte[] cipherText = Convert.FromBase64String(lines[3]);
Array.Clear(lines, 0, lines.Length);
lines = null;
GC.Collect();
var privkey = File.ReadAllText(openFileDialog2.FileName);
var key = RSA.Create();
key.ImportFromPem(privkey);
privkey = null;
byte[] secretkey;
RSAEncryptionPadding padd = RSAEncryptionPadding.OaepSHA1;
secretkey = key.Decrypt(encryptedsk, padd);
key = null;
GC.Collect();
using (var cipher = new AesGcm(secretkey))
{
byte[] decryptedData = new byte[cipherText.Length];
cipher.Decrypt(nonce, cipherText, tag, decryptedData);
Array.Clear(nonce, 0, nonce.Length);
Array.Clear(secretkey, 0, secretkey.Length);
Array.Clear(cipherText, 0, cipherText.Length);
nonce = null;
secretkey = null;
cipherText = null;
File.WriteAllBytesAsync(openFileDialog1.FileName + ".cfg", decryptedData);
Array.Clear(decryptedData, 0, decryptedData.Length);
decryptedData = null;
label1.Text = string.Format("successfuly decrypted to
{0}.cfg", openFileDialog1.FileName);
}
decrypted = true;
}
catch
{
label1.Text = "One of the files isn't correct";
GC.Collect();
}
}
GC.Collect();
}
Would love to know where I failed.
question from:
https://stackoverflow.com/questions/65859313/ram-not-being-freed-in-c-sharp-after-working-with-files 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…