Skip to content

Instantly share code, notes, and snippets.

@huobazi
Created June 22, 2011 03:04
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • 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( );
}
@Akz8
Copy link

Akz8 commented Feb 19, 2015

Thanks for this.

@amgadelsaiegh
Copy link

how would i connect this code to the main "program.cs" class ?

@JasonSantus
Copy link

This was pretty useful. Thanks a lot .

@IAMIronmanSam
Copy link

Thanks alot. Your awesome

@Svetomech
Copy link

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!

@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