Created
June 22, 2011 03:04
-
-
Save huobazi/1039424 to your computer and use it in GitHub Desktop.
Password masking in C# console application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Gets the console secure password. | |
/// </summary> | |
/// <returns></returns> | |
private static SecureString GetConsoleSecurePassword( ) | |
{ | |
SecureString pwd = new SecureString( ); | |
while ( true ) | |
{ | |
ConsoleKeyInfo i = Console.ReadKey( true ); | |
if ( i.Key == ConsoleKey.Enter ) | |
{ | |
break; | |
} | |
else if ( i.Key == ConsoleKey.Backspace ) | |
{ | |
pwd.RemoveAt( pwd.Length - 1 ); | |
Console.Write( "\b \b" ); | |
} | |
else | |
{ | |
pwd.AppendChar( i.KeyChar ); | |
Console.Write( "*" ); | |
} | |
} | |
return pwd; | |
} | |
/// <summary> | |
/// Gets the console password. | |
/// </summary> | |
/// <returns></returns> | |
private static string GetConsolePassword( ) | |
{ | |
StringBuilder sb = new StringBuilder( ); | |
while ( true ) | |
{ | |
ConsoleKeyInfo cki = Console.ReadKey( true ); | |
if ( cki.Key == ConsoleKey.Enter ) | |
{ | |
Console.WriteLine( ); | |
break; | |
} | |
if ( cki.Key == ConsoleKey.Backspace ) | |
{ | |
if ( sb.Length > 0 ) | |
{ | |
Console.Write( "\b\0\b" ); | |
sb.Length--; | |
} | |
continue; | |
} | |
Console.Write( '*' ); | |
sb.Append( cki.KeyChar ); | |
} | |
return sb.ToString( ); | |
} |
First, thank you for your time and sharing this code.
I will like to add this to your code:
else if (i.Key == ConsoleKey.Backspace)
{
//Prevent an exception when you hit backspace with no characters on the array.
if (pwd.Length>0)
{
pwd.RemoveAt(pwd.Length - 1);
Console.Write("\b \b");
}
}
and
if (!char.IsControl(i.KeyChar))
Thanx, very nice.
Super usefull. Works like a charm!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There's a serious bug here!
See, if you press any special key (e.g. Win button, Volume+/- buttons...) it will still get intercepted resulting in a screwed up password.
UPD: There's actually a quite simple fix for that. Simply check if (char.IsControl(i.KeyChar)) before appending a character. Bingo!