Masked Password in Batch Done Right

There is not much you can do about hiding confidential information (namely passwords) in batch files from a determined hacker, but you can hide keyboard input from the console -and from prying eyes over your shoulder or on a remote terminal you have logged into to run your batch script.

The trick is to "mask" the input with whatever character(s) you choose, say an asterisk or a random number of bullets for every key typed.

This has been a hot topic since 2009 in the batch scripting blogs, and I found the best answers in two Stack Overflow posts and another one from DosTips:

As paxdiablo explains in Can I mask an input text in a bat file?, taking the SET /P input from the nul: device is the clever bit: the password variable will be immediately set to an empty string and the command will not wait for input -which is completely opposite of its intended behavior.

Next, the FOR /F command parses the output of the password.exe console application and assigns it to the password variable. If you want to make things a little more cryptic, you can drop the '.exe' extension from the command—as I did.

What is notable about this solution is the combination of both DOS commands and the console application to simulate a DOS input propmt.

password.exe is a very small C# console application that processes a stdin (Console) key at a time, outputs asterisks to mask the input and returns whatever was actually typed in:

My first encounter with this code was at Password masking console application, where CraigTP used the two-step cursor dance "\b \b" to succesfully simulate the BACKSPACE key.

The only problem I had with the original code was that writing to the console had no effect on the asterisks (at least on Windows 7). Digging deeper, I came accross the final tocuh of genius: aGerman in Hide entered passwords with asterisks suggested writing the asterisks and the backspace to the stderr (Console.Error) stream, and the actual password characters to the stdout (Console) stream. The FOR /F loop processes stdout exclusively, but stderr will display whatever you put on it immediately.

Adding it all up, my versions of maskpassword.bat and password.exe produce the following output:

HJR Mask Password Utility, Version 1.0, Fri Aug 31 13:15:02 CDT 2012

Enter your password: ***********

You entered 'Hell0W0rld!'.

You would not ECHO your password in actual use of course; you would pass it on to other commands, but this is just a demo.

Once again, and as a disclaimer, there are no guarantees of safety from a knowledgeable user, but this just might discourage the ocassional hacker from going any further. As a final tip, always copy or FTP your original script before executing it!

Hector [.j.] Rivas
Hector [.j.] Rivas
Rowlett, TX | 214.789.1733 |