If I have a symmetric key in a byte[] array in C#, how can I erase it securely?

for (int i = 0; i < array.Length; i++) {
    array[i] = 0;

Is this good enough?

  • This probably belongs in stack overflow. It may be cryptography, but the question is still programmatic in nature. You'd have better luck there. – SomeGuy May 17 '18 at 20:59
  • 1
    I don't think this should be migrated to SO. This question needs a security perspective, not a programming perspective. – Anders Jun 2 '18 at 12:38

Yes, that's generally good enough.

If you are worried about residual current then you could first randomize it or use 0xFF and then 0x00 to fill the array. However, retrieving memory from the chips itself is not that easy.

Note that C# and other managed languages may shuffle / copy memory locations when memory management is performed (e.g. compacting the memory after garbage collection). The shorter the life time of the key the less chance it remains in memory somewhere.

Another issue is that the (just-in-time) compiler optimizes out the memory. The only thing against that is to actually use the memory:

byte total;
for (int i = 0; i < array.length; i++)
     total |= array[i];
if (total != 0)
    throw new Exception(); 

this makes it much harder and therefore less likely that the code will be optimized out.

And yes, doing secure coding in managed languages has a lot of advantages, but there are also disadvantages like the ones explained above.

  • 1
    I wouldn't want to bet that an intelligent optimizing compiler won't ever be able to figure out that that exception will never be hit. Also, I think C# has some sort of "secure strings" functionality that disables the GC on that string. It might be worth mentioning. – forest Jun 14 '18 at 10:33
  • You've just mentioned it :) But I would not go into that without a clear description on how to use that securely with a symmetric cipher. It's probably best to go for a cryptography service provider (CSP) that supplies native / hardware encryption if you want to go that deep. – Maarten Bodewes Jun 14 '18 at 10:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.