Monthly Archives: April 2016

Hiding passwords in (C# App) console

I’m actually a bit surprised that despite .Net/C# being more than 10 years old there is still no native Console.ReadLine() overload that hides the characters you are tying – for when you want to prompt for a password or so. Of course writing your own version to do this is not really difficult but still it would have been nice…

Here is one quick version… in case someone else wants to have one (and is too lazy to create it from scratch) hehe.

 

        private static string GetPwd()
        {
            string pass = "";
            Console.Write("Enter your password: ");
            ConsoleKeyInfo key;

            do
            {
                key = Console.ReadKey(true);

                // Backspace Should Not Work
                if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
                {
                    pass += key.KeyChar;
                    Console.Write("*");
                }
                else if (key.Key == ConsoleKey.Backspace) 
                {
                    if (pass.Length > 0)
                        pass = pass.Substring(0, pass.Length - 1);
                    Console.Write("\b \b");
                }
            }            
            // Stops Receving Keys Once Enter is Pressed
            while (key.Key != ConsoleKey.Enter); 
            Console.WriteLine();
            return pass.TrimEnd('\r', '\n'); 
        }