Microsoft's sample code for encryption / decryption in C# has an unexplained line where they pin the secret key in memory. I understand the concept of pinning well enough - it's used to indicate the GC should not move the contents of that memory to other locations. Sure, fine.
What's the benefit of pinning the secret key? I am fairly sure there is one - a very intelligent developer I worked with once upon a time mentioned that it was an important step for our software to be secure. The relevant code from MS's article.
static void Main()
{
// Must be 64 bits, 8 bytes.
// Distribute this key to the user who will decrypt this file.
string sSecretKey;
// Get the key for the file to encrypt.
sSecretKey = GenerateKey();
// For additional security pin the key.
GCHandle gch = GCHandle.Alloc( sSecretKey, GCHandleType.Pinned );
// Encrypt the file.
EncryptFile( @"C:\MyData.txt", @"C:\Encrypted.txt", sSecretKey );
// Decrypt the file.
DecryptFile( @"C:\Encrypted.txt", @"C:\Decrypted.txt", sSecretKey );
// Remove the key from memory.
ZeroMemory( gch.AddrOfPinnedObject(), sSecretKey.Length * 2 );
gch.Free();
}
It's because overwriting the memory only overwrites where the data is located now.
If the garbage collector has moved it around, there could be copies of the data remaining in its prior locations.
Why aren't you using the SecureString
class for this? Overwriting a System.String
in-place violates its invariants and could cause unexpected behavior. A SecureString
however is designed to be erased and leave no copies behind.
He's making it "more secure" by zero-ing out the memory after he's finished using it. You can't access the memory bytes directly unless you pin the object. If you don't zero out the bytes, the string will lay around in memory until the garbage collector gets around to cleaning it up.
Someone could read your process's memory and find the secret key there. Granted, someone could still do that, there's just a smaller window of time where it's accessible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With