Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Securely delete variable from memory

I'm making a security related program and I want to be sure that I'm doing this the right way. When someone logs in with a password, a secret key is decrypted and stored in a variable. When they log out, I want the data in memory for that secret key to be completely erased, not just marked as deleted. I'm currently doing the following:

public void Logout()
{
    RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();
    for (var i = 0; i < 3; i++)
    {
        byte[] data = new byte[(int) Math.Round((double) (_phraseHash.Count()))];
        rngCsp.GetBytes(data);
        int randomNum = BitConverter.ToInt32(data, 0);
        _phraseHash = randomNum.ToString();
    }
    LoggedIn = false;
    _phraseHash = null;
}

What I want to know is if this will be sufficient to completely erase the secret key (_phraseHash) from the system.

Also is this even necessary? I don't actually know much about how data in memory is deleted, I just assumed it would be somewhat similar to how hard drives work where bytes are just marked deleted and rewritten when something else needs the space.

like image 741
Hephaestious Avatar asked Sep 12 '16 10:09

Hephaestious


1 Answers

I think you might be interested in SecureString

An instance of the System.String class is both immutable and, when no longer needed, cannot be programmatically scheduled for garbage collection; that is, the instance is read-only after it is created, and it is not possible to predict when the instance will be deleted from computer memory. Because System.String instances are immutable, operations that appear to modify an existing instance actually create a copy of it to manipulate. Consequently, if a String object contains sensitive information such as a password, credit card number, or personal data, there is a risk the information could be revealed after it is used because your application cannot delete the data from computer memory.

A SecureString object is similar to a String object in that it has a text value. However, the value of a SecureString object is pinned in memory, may use a protection mechanism, such as encryption, provided by the underlying operating system, can be modified until your application marks it as read-only, and can be deleted from computer memory either by your application calling the Dispose method or by the .NET Framework garbage collector.

like image 166
Konstantin Ershov Avatar answered Sep 29 '22 19:09

Konstantin Ershov