Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mask Password Input in a Console App

I am writing a console application using BDE 2006 and I want it to be able to prompt for a password string and mask it with "*" as the user is typing. I have looked around but I could not find examples of how to do this. Everything I saw was how to do this in TEdit. Any pointers on how to accomplish this?

Thanks in advance,

Nic

like image 864
NicM Avatar asked Sep 08 '10 19:09

NicM


People also ask

How to mask a password in c#?

string pass = ""; Console. Write("Enter your password: "); ConsoleKeyInfo key; do { key = Console. ReadKey(true); // Backspace Should Not Work if (key. Key !=

What is password masking?

Password masking is the act of hiding passwords as bullets or asterisks when the user enters the password. Password masking is an attempt to protect the user against shoulder surfers who look at the screen.

How do I add a console application?

Open Visual Studio, and choose Create a new project in the Start window. In the Create a new project window, select All languages, and then choose C# from the dropdown list. Choose Windows from the All platforms list, and choose Console from the All project types list.


2 Answers

Here's a working solution:

program Project2;

{$APPTYPE CONSOLE}

uses
  SysUtils, Windows;

function GetPassword(const InputMask: Char = '*'): string;
var
  OldMode: Cardinal;
  c: char;
begin
  GetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), OldMode);
  SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), OldMode and not (ENABLE_LINE_INPUT or ENABLE_ECHO_INPUT));
  try
    while not Eof do
    begin
      Read(c);
      if c = #13 then // Carriage Return
        Break;
      Result := Result + c;
      if c = #8 then // Back Space
        Write(#8)
      else
        Write(InputMask);
    end;
  finally
    SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), OldMode);
  end;
end;

begin
  try
    Writeln(Format(sLineBreak + 'pswd=%s',[GetPassword]));
    Readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

Update: Note that the above code handles the BackSpaces visually, but keeps them embedded in the password, which might not be what you want.
In that case the following code would filter them out:

  if c = #13 then // Carriage Return
    Break;
  if (c = #8) and (Length(Result) > 0) then  // Back Space
  begin
    Delete(Result, Length(Result), 1);
    Write(#8);
  end
  else
  begin
    Result := Result + c;
    Write(InputMask);
  end;
like image 168
Francesca Avatar answered Oct 19 '22 18:10

Francesca


I have a unit with procedure ConsoleGetPassword(const caption: String; var Password: string); which does what you want

see http://gist.github.com/570659

like image 25
jasonpenny Avatar answered Oct 19 '22 18:10

jasonpenny