#950 – PasswordBox Allows Entering a Password
November 14, 2013 5 Comments
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>
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); }
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.
Agreed. The SecurePassword is covered in an upcoming post. This post just introduced the control and the Password property.
Do you mean that PasswordBox.Password property is initialized only on demand?
Yes, when you read the Password property, the data is unencrypted and passed back to you.
Pingback: #956 – PasswordBox Stores Password as a SecureString | 2,000 Things You Should Know About WPF