Quantcast
Channel: .NET Framework Class Libraries forum
Viewing all articles
Browse latest Browse all 8156

Clearing memory

$
0
0

I'm seeking advice on ensuring I've cleared memory that previously contained sensitive data.

My application (c# .net 4.5, WPF) handles sensitive information.  The data comes in as clear text and I promptly encrypt it and then attempt to overwrite the memory that previously held the sensitive data in clear text.  Except for the case of"string", using the memory watch I can see that my memory is overwritten as I want, but this leaves me with 2 questions:

(1) How do I explicitly overwrite the memory allocated by "string"

(2) Since C# handles memory automagically, can I be 100% sure that the code below will always overwrite memory as expected?

Here's what I'm doing:


string sClearTextData = "My sensitive data";
IFormatter form = new BinaryFormatter();
MemoryStream ser = new MemoryStream();
form.Serialize(ser, (object)sClearTextData);
byte[] clearData = ser.ToArray();

// Now ser._buffer and clearData both contain clear text data

byte[] encryptedData = EncryptMyStuff(clearData);

// Now it's time to clean up the memory that previously held my clear text data

// Overwrite the string - ERROR This does NOT overwrite the allocated memory
sClearTextData = "xxxxxxxxxxxxxxxxx";

// Clear the byte array
for (int i = 0; i < clearData.Count(); i++) { clearData[i] = 0; }

// Now clear the memory stream by overwriting all allocated memory with encrypted data
// Reset the stream index so we begin writing at the start of allocated memory
ser.SetLength(0);
// Now overwrite. encryptedData size is identical to clearData size
for.Serialize(ser, (object)encryptedData);

// Is all my clear text data gone from memory now? 



Viewing all articles
Browse latest Browse all 8156

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>