Joe
Joe

Reputation: 2564

WPF PasswordBox & SecureString: Can't MakeReadOnly()?

Is it possible to mark the PasswordBox.SecurePassword as ReadOnly?

Consider this simple code:

XAML:

<StackPanel>
    <PasswordBox Name="pBox" MinWidth="100" />
    <Button Content="OK" Click="Button_Click" Width="50" />
</StackPanel>

C#:

private void Button_Click(object sender, RoutedEventArgs e)
{
    pBox.SecurePassword.MakeReadOnly();
    Console.WriteLine(pBox.SecurePassword.IsReadOnly());
}

It will output False. Why?

EDIT: Just to make sure, I tried this and it output "True" as expected.

private void Button_Click(object sender, RoutedEventArgs e)
{
    SecureString s = new SecureString();
    s.MakeReadOnly();
    Console.WriteLine(s.IsReadOnly());
}

Upvotes: 1

Views: 2224

Answers (1)

GameScripting
GameScripting

Reputation: 17022

pBox.SecurePassword will return an new instance of secure string each time you read the property. You can validate it by calling GetHashCode on pBox.SecurePassword multiple times.

You'll also notice that using Visual Studios "Make object id" does not display #X, because its an new instance every time you hover with the mouse.

When creating a reference to a SecureString object into a local variable it is the same instance that you called MakeReadOnly() on, so it behaves as expected.

Upvotes: 1

Related Questions