#950 – PasswordBox Allows Entering a Password

You can use a PasswordBox control to allow a user to enter a password.  The PasswordBox looks like a TextBox, but shows a uniform mask character as you type, to hide the characters that you are typing.  By default, this mask character appears as a filled circle.

In the example below, the user can enter a password into the PasswordBox.  As the user enters their password, the characters are shown using the mask character.

    <StackPanel>
        <StackPanel Orientation="Horizontal" Margin="10">
            <Label Content="Password:"/>
            <PasswordBox Name="pwbPassword"
                         Width="150" Margin="5,0"/>
        </StackPanel>
        <Button Content="Show everybody my Password"
                HorizontalAlignment="Center"
                Padding="10,5"
                Click="Button_Click"/>
    </StackPanel>

950-001
You can read the contents of a PasswordBox by reading its Password property.  This property is just a string containing the password that they entered.

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(pwbPassword.Password);
        }

950-002

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

5 Responses to #950 – PasswordBox Allows Entering a Password

  1. You should never use Password to read the password out of a PasswordBox. This is bad advice, because it exposes the password in process memory as a garbage collected plaintext string with an indeterminate lifetime. This allows other application to get at the password by viewing the WPF process’ memory. Instead, you should use SecurePassword to get the password out as an encrypted SecureString. Then, when you need to actually access the password characters in plaintext, you can go through a BSTR whose lifetime you have 1) explicit control over and 2) you’d want to make as short as possible to minimize the risk of external accessibility.

  2. Pingback: #956 – PasswordBox Stores Password as a SecureString | 2,000 Things You Should Know About WPF

Leave a comment