Q:

Clearing out a c# byte array with sensitive data

I have a c# byte[] containing sensitive data. 
What is the best way to clear it?
How do I ensure that something like Array.Clear will not be optimized away?

A:

I cannot think of any circumstance in which a call to Array.Clear would ever be optimized away and even if it could it would only be optimized away in instances where your byte[] was cleared already.
Edit: Something else to consider would be finding out if the framework's SecureString implementation would be useful in your situation:

A SecureString object is similar to a
  String object in that it has a text
  value. However, the value of a
  SecureString object is automatically
  encrypted, can be modified until your
  application marks it as read-only, and
  can be deleted from computer memory by
  either your application or the .NET
  Framework garbage collector

A:

Even if Array.Clear is guarenteed to be executed (not optimized away) I think you still may have a problem.  The GC can move objects around in the heap and there is no guarentee that traces of the original byte will linger if it was moved from one location to another before Array.Clear was called.
You may want to check out SecureString, ProtectedData, or ProtectedMemory.  But, if you want a more manual approach I think you are going to have to at least pin the byte array so that the GC cannot move it around.  I believe the SecureString uses this trick as well.

