Skip to content

Instantly share code, notes, and snippets.

@huobazi
Created June 22, 2011 03:04
Show Gist options
  • Save huobazi/1039424 to your computer and use it in GitHub Desktop.
Save huobazi/1039424 to your computer and use it in GitHub Desktop.
Password masking in C# console application
/// <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( );
}
@ChristianC83
Copy link

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))

@iglasner
Copy link

Thanx, very nice.

@Frau87
Copy link

Frau87 commented Oct 27, 2022

Super usefull. Works like a charm!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment