var self = justin();

Software Developer Teammate

A place to remind my future self of what I've learned and experienced. That means both my successes and failures.


Masking Console Password in .NET

I pieced this together to mask some console input when a user needed to enter a password. Simple, but not meant to be secure as it still uses string. Based on this stackoverflow answer.

    private static string GetPassword()
    {
        var password = new StringBuilder(16);

        while (true)
        {
            var keyInfo = Console.ReadKey(intercept: true);
            switch (keyInfo.Key)
            {
                case ConsoleKey.Enter:
                    return password.ToString();

                case ConsoleKey.Backspace:
                    if (password.Length > 0)
                    {
                        password = password.Remove(password.Length - 1, 1);
                        Console.Write("\b \b");
                    }
                    break;
                default:
                    password.Append(keyInfo.KeyChar);
                    Console.Write("*");
                    break;
            }
        }
    }
comments powered by Disqus