Mega Code Archive

 
Categories / C# Tutorial / Security
 

Read password from console

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();              } }