Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C command-line password input

Tags:

c

passwords

input

I want to allow users to enter password using command-line interface. but I don't want to display this password on screen (or display "****").

How to do it in C? Thanks.

Update:

I'm working on Linux only. So I don't actually care about Win or other systems. I tried Lucas' solution and it worked fine. However, I still have another question:

  1. If this is a single process & single thread app, changing setting of termios affects different terminals?

  2. How about 1 process - multi threads, multi processes - multi threads?

Thanks very much.

like image 587
user397232 Avatar asked Nov 23 '09 22:11

user397232


2 Answers

If your system provides it, getpass is an option:

#include <unistd.h>
/* ... */
char *password = getpass("Password: ");

This will not display anything as characters are typed.

like image 158
LnxPrgr3 Avatar answered Sep 28 '22 02:09

LnxPrgr3


The function getpass is now obsolete. Use termios.

#include <termios.h>
#include <stdio.h>

void get_password(char *password)
{
    static struct termios old_terminal;
    static struct termios new_terminal;

    //get settings of the actual terminal
    tcgetattr(STDIN_FILENO, &old_terminal);

    // do not echo the characters
    new_terminal = old_terminal;
    new_terminal.c_lflag &= ~(ECHO);

    // set this as the new terminal options
    tcsetattr(STDIN_FILENO, TCSANOW, &new_terminal);

    // get the password
    // the user can add chars and delete if he puts it wrong
    // the input process is done when he hits the enter
    // the \n is stored, we replace it with \0
    if (fgets(password, BUFSIZ, stdin) == NULL)
        password[0] = '\0';
    else
        password[strlen(password)-1] = '\0';

    // go back to the old settings
    tcsetattr(STDIN_FILENO, TCSANOW, &old_terminal);
}

int main(void)
{
    char password[BUFSIZ];

    puts("Insert password:");
    get_password(password);
    puts(password);
}
like image 34
Henrique Gouveia Avatar answered Sep 28 '22 01:09

Henrique Gouveia