C命令行密码输入

use*_*232 13 c passwords input

我想允许用户使用命令行界面输入密码.但我不想在屏幕上显示此密码(或显示"****").

怎么用C做?谢谢.

更新:

我只在Linux上工作.所以我实际上并不关心Win或其他系统.我试过卢卡斯的解决方案,它工作得很好.但是,我还有另一个问题:

  1. 如果这是一个单一进程和单线程应用程序,更改termios的设置会影响不同的终端?

  2. 1个进程怎么样 - 多线程,多进程 - 多线程?

非常感谢.

Lnx*_*gr3 17

如果您的系统提供它,getpass是一个选项:

#include <unistd.h>
/* ... */
char *password = getpass("Password: ");
Run Code Online (Sandbox Code Playgroud)

键入字符时不会显示任何内容.


Luc*_*cas 10

如果您使用的是UNIX环境,则可以关闭命令行的ECHO.

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

#define SIZE 100

void getPassword(char password[])
{
    static struct termios oldt, newt;
    int i = 0;
    int c;

    /*saving the old settings of STDIN_FILENO and copy settings for resetting*/
    tcgetattr( STDIN_FILENO, &oldt);
    newt = oldt;

    /*setting the approriate bit in the termios struct*/
    newt.c_lflag &= ~(ECHO);          

    /*setting the new bits*/
    tcsetattr( STDIN_FILENO, TCSANOW, &newt);

    /*reading the password from the console*/
    while ((c = getchar())!= '\n' && c != EOF && i < SIZE){
        password[i++] = c;
    }
    password[i] = '\0';

    /*resetting our old STDIN_FILENO*/ 
    tcsetattr( STDIN_FILENO, TCSANOW, &oldt);

}


int main(void)
{
    char password[SIZE];
    printf("please enter password\n");
    getPassword(password);

    printf("Do something with the password <<%s>>\n", password);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)


Hen*_*eia 5

函数getpass现在已过时。使用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);
}
Run Code Online (Sandbox Code Playgroud)


ste*_*anB 2

对于 C/命令行/linux,请参阅:

man getch
man noecho
Run Code Online (Sandbox Code Playgroud)

getch请参阅about中的评论noecho。我自己从来没有尝试过这个。

在 bash 中如果使用read -s它不会在屏幕上回显:

> read -s x
<type something><enter>
> echo $x
<whatever you typed>
Run Code Online (Sandbox Code Playgroud)