Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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 commented Feb 19, 2015

Thanks for this.

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

This was pretty useful. Thanks a lot .

Thanks alot. Your awesome

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!

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))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment