Often we are developing an application that interacts with the user asking for the password and if he is doing it in the presence of someone or recording a video, the password will appear.
On most systems like UNIX this is already hidden by default. So let’s see how to do it with C++ .
For this we will need to include the following headers:
iostream
is already known and commonly used by us.
termios.h
is a library that contains the definitions used by the I/O interfaces of terminal , it will be with it that we will hide the typed.
And unistd.h
is a library that provides access to the POSIX operating system API and makes it compatible with any operating system and compiler.
After adding the headers, just:
termios
tcgetattr()
functiontermios
, but this time to replicate the data from the previous instance so we can changetcsetattr()
function after establishing the rule: newt.c_lflag &= ~ECHO;
std::cout
, getline()
and std::cin
, storing in a pre-declared variabletcsetattr
, but to return to the initial instance.
Also in the code we added the data display (on the same line with
\r
) typed just for didactic reasons.
The code in short looks like this
vim hidden.cpp
Compile and run:
g++ hidden.cpp && ./a.out
Example:
Hide input, show password.
If during the optional std::cout
you still want to replace the std::string
with asterisks(*
), add this snippet to your code:
It will appear:
Your password is: ************
.
Example:
Hide input, show asterisks.
We can see that the command in the terminal stty -echo
(to hide the data typed in the terminal) and stty echo
to return the display do the same thing. Note that the stty
program/command makes use of the termios.h
library.
I see a lot of people asking this question on StackOverflow and honestly I’ve never seen an effective solution that actually solves it the way one wants, not even using the curses.h
library(Note, curses.h
, also compiles with: -lcurses -ltinfo
, not NCURSES) .
So, I created a way that solves this in a simple way, using do while
, excluding getline()
and using getchar()
instead:
Only the magic is on the line:
newt.c_lflag &= 'a';
, I replaced the~ECHO
with any letter/character, in this'a'
.
It will appear:
Enter your password: ************
, that is, asterisks instead of empty.
Example:
Input asterisks, show password.