【问题标题】:How to mask password in c?如何在c中屏蔽密码?
【发布时间】:2010-12-17 18:17:08
【问题描述】:

在 C 语言中,我想将用户键入的每个字符显示为 * (例如,请输入您的密码:*****)

我正在四处寻找,但找不到解决方案。 我在 Ubuntu 上工作。有人知道什么好方法吗?

【问题讨论】:

标签: c linux passwords


【解决方案1】:

看看ncurses 库。这是一个非常宽松的许可库,在各种系统上具有大量功能。我用的不多,所以我不确定你想调用哪些函数,但如果你看看documentation,我相信你会找到你想要的。

【讨论】:

    【解决方案2】:

    查看我的代码。它适用于我的 FC9 x86_64 系统:

    #include <stdio.h>
    #include <string.h>
    #include <unistd.h>
    #include <termios.h>
    
    int main(int argc, char **argv)
    {
            char passwd[16];
            char *in = passwd;
            struct termios  tty_orig;
            char c;
            tcgetattr( STDIN_FILENO, &tty_orig );
            struct termios  tty_work = tty_orig;
    
            puts("Please input password:");
            tty_work.c_lflag &= ~( ECHO | ICANON );  // | ISIG );
            tty_work.c_cc[ VMIN ]  = 1;
            tty_work.c_cc[ VTIME ] = 0;
            tcsetattr( STDIN_FILENO, TCSAFLUSH, &tty_work );
    
            while (1) {
                    if (read(STDIN_FILENO, &c, sizeof c) > 0) {
                            if ('\n' == c) {
                                    break;
                            }
                            *in++ = c;
                            write(STDOUT_FILENO, "*", 1);
                    }
            }
    
            tcsetattr( STDIN_FILENO, TCSAFLUSH, &tty_orig );
    
            *in = '\0';
            fputc('\n', stdout);
    
            // if you want to see the result: 
            // printf("Got password: %s\n", passwd);
    
            return 0;
    }
    

    【讨论】:

    • 使用此代码,如果用户输入退格键,它将显示为 。有没有办法支持在通过 write(STDOUT_FILENO, "", 1) 写入后通过退格删除输入?
    【解决方案3】:

    使用这样的程序 问我更多问题

    此程序用于放置 * 而不是 char 并在使用退格键后删除输入 ^^

    #include <stdio.h>
    #include <stdlib.h>
    #include <conio.h>
    
    int main()
    {
        char a[100],c;
        int i;
        fflush(stdin);
        for ( i = 0 ; i<100 ; i++ )
        {
    
            fflush(stdin);
            c = getch();
            a[i] = c;
            if ( a[i] == '\b')
            {
                printf("\b \b");
                i-= 2;
                continue;
            }
            if ( a[i] == ' ' || a[i] == '\r' )
                printf(" ");
            else
                printf("*");
            if ( a[i]=='\r')
                break;
        }
        a[i]='\0';
    
        printf("\n%s" , a);
    }
    

    【讨论】:

      【解决方案4】:

      手动操作;一次读取输入一个字符,例如 conio 中的 getch(),并为每个字符打印一个 *。

      【讨论】:

      • conio.h 是 windows 中的头文件。我正在使用ubuntu。我该怎么做?
      • 那么你可能想要使用一个 curses 库。
      猜你喜欢
      • 2011-02-01
      • 2019-04-30
      • 1970-01-01
      • 2016-01-21
      • 2013-04-19
      • 2017-10-02
      • 2015-09-11
      • 2017-09-08
      • 2011-10-31
      相关资源
      最近更新 更多