Friday, October 29, 2010

Interactive Password on Console app with C#

If you've ever used C# for application development and needed to get a password into your program but don't want to display it to the screen, you'll realise that you will need to use some COM objects and kernel functionality.
This simple example provides you with a template to get the password from a user without displaying on the screen what they typed, and also accepting the backspace key when they press it.
The code;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Runtime.InteropServices;

namespace FirstOne
{
class Program
{
// Get the kernel function for setting console modes
[System.Runtime.InteropServices.DllImport("kernel32 ")]
private static extern int SetConsoleMode(IntPtr hConsoleHandle, int dwMode);
// Get the kernel function for getting console modes
[System.Runtime.InteropServices.DllImport("kernel32 ")]
private static extern int GetConsoleMode(IntPtr hConsoleHandle, ref int dwMode);

// Some useful constants for the console values
private const int ENABLE_LINE_INPUT = 2;
private const int ENABLE_ECHO_INPUT = 4;
// Standard input file handle
private const int CONIN = 3;

// Ensure that our process is single threaded as we as using COM and need to ensure communication
[STAThread]
static void Main(string[] args)
{
IntPtr hStdIn = new IntPtr(CONIN);
int myMode=0;
char inputChar;
string password = "";
Console.Write("Password: ");
// Get the current console settings
GetConsoleMode(hStdIn, ref myMode);
// Turn off echo
myMode = (myMode & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT));
SetConsoleMode(hStdIn, myMode);

do
{
inputChar = (char)Console.Read();
if (inputChar == '\b') // Can also use 8 instead of '\b'
{
// Delete character if user has pressed backspace
password=password.Remove(password.Length-1);
}
if (inputChar >= 32)
{
// Store password characters
password += inputChar;
}
} while (inputChar != '\r');

// Reset terminal echo
myMode = (myMode | (ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT));
SetConsoleMode(hStdIn, myMode);
Console.WriteLine("");
Console.WriteLine("Password was: {0}", password);
}
}
}

No comments:

Post a Comment