Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing a System.String in C#

Tags:

c#

Will this overwrite the contents of my string:

unsafe
{
    fixed (char* chars = str)
    {
        for (int i = 0; i < str.Length; i++)
            chars[i] = '1';
    }
}

The background is I'm using NetworkCredientials, in which you set the password using a plain old System.String. I'd like to "clear it" afterwards, if that's possible. Any suggestions on how to do this are welcome, but the main question is to understand if fixed will really give me access to the underlying char array. Thanks!

Edit

I would like to understand what is going on here - if a string object is immutable, and fixed doesn't let the object move then what's happening in the code posted? Where are those characters being written to?

like image 401
noelicus Avatar asked Dec 01 '22 02:12

noelicus


1 Answers

Use the NetworkCredentials constructor overload taking SecureString instead. The whole reason for that overload is to avoid this problem. You shouldn't go trying to mutate System.String instances. (It's certainly possible with reflection, but should be avoided.)

like image 168
Jon Skeet Avatar answered Dec 12 '22 06:12

Jon Skeet