How to hide the password typed by user in the console?

I want to let user type the password but the password should not be printed on the console, just like git tool does, how can I do? Or is there any crate contained this function? It is better if it can print as much *s as the characters in the password. Thanks.

1 Like

This might help: GitHub - mikedilger/echo_off: Simple rust mechanism to disable/enable terminal echo on linux systems

1 Like

You will need to turn off echo for the terminal. In C that would be something like:

struct termios raw;
tcgetattr(STDIN_FILENO, &raw);
raw.c_lflag &= ~(ECHO);
tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw);

make sure to enable echo again afterwards and preferably also register a SIGKILL and SIGINT signal handler that enables echo again.

You can use rpassword crate for this. rpassword crate uses tcgetattr/tcsetattr on Unix and GetConsoleMode/SetConsoleMode on Windows.


Thanks, I'll take a look. But in my experience in nodejs, hiding characters can be done by insert a series of specified characters, which is the similar to the way to changing background and text colors?

The termios attributes are at a lower level than terminfo capabilities like color escapes. There's ways to fake it with terminfo capabilities but I've yet to see a good one (invis is unreliable, color based still echos copy-able characters, etc).


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.