3

My application requires the user to enter a password like so:

using (var passwordForm = new PasswordForm())
{
    var result = passwordForm.ShowDialog();
    if (result == DialogResult.OK)
    {
        password = new SecureString();
        foreach(var c in passwordForm.PasswordBox.Text)
        {
            password.AppendChar(c);
        }
    }
}

With password being a SecureString field which holds on to the password for quite some time.

Obviously, PasswordField.Text is just a regular unencrypted string, which means the user's password is exposed. There isn't really a way around this (as far as I know) so it's a necessary evil. Because of this, I want the period of time during which the password is exposed to be as short as possible.

What's the best way to achieve this? The password form will be disposed as soon as I'm done with it, but would this actually remove all 'plaintext occurrences' of the password from memory? And if not, what's the best way to ensure that this will happen as soon as possible?

Johan Geluk
  • 149
  • 2
  • 8
  • Quick and dirty... Why not just set the password box's text to something different as soon as you load it into the secure string? – UnhandledExcepSean Jun 25 '15 at 00:11
  • @Ghost I think `String` immutability would mean you only succeeded in creating a second string in memory. Timely disposal of the form, and as such, the Textbox is the real cleanup here. Meaning it would come down to how quickly GC gets to it. – DonBoitnott Jun 25 '15 at 11:05
  • I'm curious about your use case. Are you worried about a virus stealing the password? If so then you probably want a custom solution as mentioned elsewhere on SO. SecureString is really just for hiding the password if you accidentally write it to a log or crash report. http://stackoverflow.com/questions/6982236/how-is-securestring-encrypted-and-still-usable. – Charlie Jun 25 '15 at 16:35

1 Answers1

1

I believe this is already answered here, but let me summarize my understanding:

  • The use case for SecureString is to prevent the developer from accidentally showing a password to someone in a log or crash report.
  • If you are concerned about a virus stealing your password out of memory than even encrypting it won't help because at somepoint you will need to decypt it (as explained here) at which point the virus can just get the password.
  • You could create a custom control like this one that uses a SecureString for the text box, but I would question what the point is. Unless you create log entries or crash reports by dumping everything in memory there probably isn't a point.
Community
  • 1
  • 1
Charlie
  • 2,004
  • 6
  • 20
  • 40