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?