1

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());
}
Joe
  • 2,496
  • 1
  • 22
  • 30

1 Answers1

1

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.

GameScripting
  • 16,092
  • 13
  • 59
  • 98
  • Thanks, this explains it perfectly. Do you have any idea why it was designed to return a copy of the SecureString? An extra layer of security? – Joe Nov 20 '12 at 21:14
  • 1
    I think since the `SecurePassword` is readonly, they really want it to be *read only*, so since `SecureString` is a reference type one could manipulate that instance, so it wouldn't be read only in they sence of immutable objects (like `System.String` is). – GameScripting Nov 20 '12 at 21:19