Hiding Password

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have created a console based application using C# which asks for the user identification to work using that system. Now, the problem is that i'm not able to hide or encrypt the password on the screen. I want to make it like "LINUX" in which only the user name is shown to the user and not the password. Can you provide some information on how I can implement this thing using C# (Remember it's a console based application)?
 
The console is created by default in line input mode. To do what you want to
do you need to use GetConsoleMode and SetConsoleMode to turn off line input
mode and character echo. The following is a quick and dirty example(watch
for line wrap):

using System;

namespace Whatever
{
class Class1
{
[System.Runtime.InteropServices.DllImport("kernel32")]
private static extern int SetConsoleMode(IntPtr hConsoleHandle,
int dwMode);

[System.Runtime.InteropServices.DllImport("kernel32")]
private static extern int GetConsoleMode(IntPtr hConsoleHandle,
ref int dwMode);

private const int ENABLE_LINE_INPUT = 2;
private const int ENABLE_ECHO_INPUT = 4;

private const int CONIN = 3;

[STAThread]
static void Main(string[] args)
{

IntPtr hStdIn = new IntPtr(CONIN);
int mode;
char inputChar;
string userName = null;
string password = "";

Console.WriteLine("Please enter your user name:");
userName = Console.ReadLine();

Console.WriteLine("Please enter your password:");

//Set console mode to read a character
//at a time and not echo input.
GetConsoleMode(hStdIn, ref mode);
mode = (mode & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT));
SetConsoleMode(hStdIn, mode);

//Read the password a character at a time.
do
{
inputChar = (char)Console.Read();
if (inputChar >= 32)
{
//Echo character with password mask.
password += inputChar;
Console.Write("*");
}
} while (inputChar != '\r');//Enter pressed end of password.

//Set console back to line input
//mode if that's what you want.
//mode = (mode | (ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT));
//SetConsoleMode(hStdIn, mode);

Console.WriteLine("");

if (password == "Let me in")
{
Console.WriteLine("Welcome " + userName);
}
else
{
Console.WriteLine("Sorry, " + userName);
}
Console.Write("Press any key to continue...");
Console.Read();

}
}
}

Nitin said:
I have created a console based application using C# which asks for the
user identification to work using that system. Now, the problem is that i'm
not able to hide or encrypt the password on the screen. I want to make it
like "LINUX" in which only the user name is shown to the user and not the
password. Can you provide some information on how I can implement this thing
using C# (Remember it's a console based application)?
 
Back
Top