How can I read a password without echoing it in C?

I’m trying to figure out how to disable the echo flag in C. I want to do this because I am coding a C program that must ask for a users password, so I would like to disable Echo, let the user enter his password, then re-enable Echo.

Before I show you the solution in C, I want to start by demonstrating how to do this in a shell script, because they both demonstrate how to solve the problem and they both show that the solution is to learn just a bit about the keyboard device driver.
Specifically, we Unix old-timers refer to it as the tty, quite literally teletypewriter or teletype device. Think late 60’s clattering printer / keyboard hooked up via a thick wire to a computational device the size of a small washing machine and you’d be on the money.
This device name is still around, and in fact the keyboard driver is still called the “tty”. Try it, type tty on the command line in Linux:

$ tty
/dev/ttys000

Amazing, isn’t it? Thirty years later…
On the Linux command line, the utility that lets you change the settings of this “tty” command is stty, and here’s exactly how you could use this to turn off echo temporarily in a shell script to ask for a password:

save_state=$(stty -g)

/bin/echo -n “Account: “
read acct
/bin/echo -n “Password: “
stty -echo
read password # this won’t echo
stty “$save_state”

echo “”
echo account = $acct and password = $password

When run, it looks like this:

Account: test
Password:
account = test and password = demo

Now, finally, let’s convert that to a C program.
Fortunately, there’s a very useful function in C that’s widely available called getpasswd() which does all the “stty” heavy lifting. It makes things easy:

#include <stdio.h>
#include <string.h>
#include <pwd.h>
#include <unistd.h>

main()
{
  char acct[80], password[80];

  printf(“Account: “);
  fgets(acct, 80, stdin);

  acct[strlen(acct)-1] = 0; /* remove carriage return */

  strncpy(password, getpass(“Password: “), 80);
  printf(“You entered acct %s and pass %s\n”, acct, password);
}

If you want to do something more sophisticated where you output an asterisk each time they enter a character, you can check out some of the example code on the Ubuntu forums discussion.

2 thoughts on “How can I read a password without echoing it in C?”

  1. If you use Bash, the read command has the -s option to not echo characters to the terminal, and the -p option to show a prompt:
    read -s -p “Password: ”
    So the example could be written as:
    read -p “Account: ” acct
    read -s -p “Password: ” password # this won’t echo
    echo
    echo account = $acct and password = $password
    Thanks for the C sample code.

    Reply

Leave a Comment

Receive My Weekly Email Newsletter:

Your email address:*
First Name
Please enter all required fields Click to hide
Correct invalid entries Click to hide

Recent Posts

On My YouTube Channel

Date Archives