#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 .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: