Read password from console : SecureString « Security « C# / CSharp Tutorial






using System;
using System.Management;
using System.Security;

public class RemoteConnect
{
    public static void Main()
    {
        SecureString password = new SecureString();
        Console.WriteLine("Enter password: ");

        ConsoleKeyInfo nextKey = Console.ReadKey(true);

        while (nextKey.Key != ConsoleKey.Enter)
        {
            if (nextKey.Key == ConsoleKey.Backspace)
            {
                if (password.Length > 0)
                {
                    password.RemoveAt(password.Length - 1);
                    // erase the last * as well
                    Console.Write(nextKey.KeyChar);
                    Console.Write(" ");
                    Console.Write(nextKey.KeyChar);
                }
            }
            else
            {
                password.AppendChar(nextKey.KeyChar);
                Console.Write("*");
            }
            nextKey = Console.ReadKey(true);
        }
        password.MakeReadOnly();
        
    }
}








35.16.SecureString
35.16.1.Instantiates a new SecureString object by passing its constructor a pointer to a character array.
35.16.2.Read password from console