C command-line password input

后端 未结 7 848
长情又很酷
长情又很酷 2020-12-03 15:00

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?

7条回答
  •  佛祖请我去吃肉
    2020-12-03 15:14

    To do this in a portable way you will need to use a standardized or de-facto standard library.

    See man 3 termios and man 3 ncurses.

    Here is a program that will work on Linux and other Unix systems...

    #include 
    
    int main(void) {
      int f = open("/dev/tty", 0);
      char s[100];
    
      system("stty -echo > /dev/tty");
      f >= 0 && read(f, s, sizeof s) > 0 &&  printf("password was %s", s);
      system("stty echo > /dev/tty");
      return 0;
    }
    

    A number of improvements are possible. Using termios would probably be better, and it would avoid the fork and possible security issues of system(). Using standard I/O to read the password would probably be better. (As written the typed newline would have to be deleted.) There is a getpass() function in Linux and some others however it is marked as "obsolete. Do not use it.". It might be a good idea to deal with SIGTSTP.

    Overall, I might look for an existing solution that deals with all these little issues...

提交回复
热议问题