LINUX C实现密码输入不回显

本文介绍如何在Linux环境下实现密码输入时不显示字符的方法。通过C语言编程使用tcgetattr和tcsetattr函数来禁用回显,同时展示了如何在Shell脚本中利用stty命令达到相同效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文:http://blog.chinaunix.net/uid-20754793-id-177771.html

 

linux C 下没有getch()函数,于是上网查了查资料,

发现可以C语言可通过使用tcgetattr函数和tcsetattr函数来实现

/* Standard C header */
#include <stdio.h>        /* for getchar(), printf() */
/* POSIX headers */
#include <termios.h>        /* for tcxxxattr, ECHO, etc */
#include <unistd.h>        /* for STDIN_FILENO */
#define LENGTH 8        /*Password length */
int main(void)
{
    char password[LENGTH];
    int len = 0;
    int ch;
    struct termios oldt, newt;
    printf("please input you password:");
    while (1) {
        if (len < LENGTH) {
            tcgetattr(STDIN_FILENO, &oldt);
            newt = oldt;
            newt.c_lflag &= ~(ECHO | ICANON);
            tcsetattr(STDIN_FILENO, TCSANOW, &newt);
            ch = getchar();
            printf("*");
            tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
        } else {
            printf("\nPassword must less then 8\n");
            break;
        }
        len = len + 1;
    }
    return 0;
}

 

#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include "Base64.c"  
//Base64编码程序int getch(void);
main(){
        char str1[20],str2[60];
        char ch;
        int i=0;
        printf("Please enter your password: ");
        while((ch=getch())!=13 ) //按回车键退出        
        {
                  str1[i++]=ch;
          putchar('*');
        }        str1[i]='\0';
        printf("\n Your input is: %s\n",str1);
        strcpy(str2,base64_encode(base64_encode(str1)));
        printf("Encoding string is: %s\n",str2);
     }
     
     //参考http://blog.youkuaiyun.com/liuchao35758600/article/details/6419499
     
     int getch(void)
     {        
      struct termios tm, tm_old;
        int fd = STDIN_FILENO, c;
        if(tcgetattr(fd, &tm) < 0)
             return -1;
        tm_old = tm;
        cfmakeraw(&tm);
        if(tcsetattr(fd, TCSANOW, &tm) < 0)
                        return -1;
        c = fgetc(stdin);
        if(tcsetattr(fd, TCSANOW, &tm_old) < 0)
                        return -1;
        if(c == 3)
         exit(1);
  //按Ctrl+C结束退出
          return c;
 }
有兴趣可以研究下Unix下的一个头文件curses.h,贴一个网站大家看下
http://www.tsnc.edu.cn/default/tsnc_wgrj/doc/curses.html

 

SHELL实现不回显

 

(1)方法就是:

stty -echo #设置输入字符不回显

#此处用read语句接收用户输入的内容

stty echo #取消不回显状态

#!/bin/bash
passwd=""
echo -n "Please input password:"
stty -echo
read passwd
echo 
stty echo

echo "The password is $passwd"

(2)其实shell中的 read的-s选项直接就可以实现输入内容不回显。如下实现
#!/bin/bash
passwd=""
echo -n "Please input password:"
read -s passwd
echo 
echo "The password is $passwd"

### C语言输入回显的原因 在标准的C语言环境中,默认情况下,字符输入会显示在终端上。然而,在某些特定场景下,可能希望隐藏用户的输入,比如密码输入时。这通常通过修改终端设置来实现。 对于Linux环境下的程序,`conio.h`库并适用,因为这是Windows特有的头文件[^3]。为了实现Linux环境下输入回显的效果,可以通过调用系统命令临时关闭终端的回显功能: ```c #include <stdio.h> #include <stdlib.h> void getPasswd(const char *prompt) { char c; int i = 0; char passwd[64]=""; printf("%s", prompt); system("stty -echo"); // 关闭输入回显 while ((c=getchar()) != '\n') { passwd[i++] = c; } passwd[i] = '\0'; system("stty echo"); // 打开输入回显 putchar('\n'); } ``` 上述代码展示了如何利用`system()`函数执行shell指令改变终端属性的方法。具体来说,`stty -echo`用于禁用按键回显;相反地,`stty echo`恢复默认行为。 ### 实现跨平台兼容性的解决方案 考虑到同操作系统之间的差异,如果想要编写能够同时适用于Windows和Unix-like系统的应用程序,则应该考虑采用更通用的方式处理这个问题。POSIX标准提供了一套接口允许开发者调整TTY设备的行为而依赖于具体的OS特性。例如,可以使用`termios`结构体中的成员变量配置新的终端模式并应用到当前会话中。 下面给出一段基于POSIX API的例子,它可以在大多数类UNIX平台上工作良好: ```c #ifdef __unix__ #include <unistd.h> /* POSIX */ #elif defined(_WIN32) #include <windows.h> /* Windows API */ #endif #include <stdio.h> #include <string.h> #include <termios.h> void disableEchoMode(int fd, struct termios* orig_termios){ tcgetattr(fd, orig_termios); /* save the terminal attributes */ struct termios raw = *orig_termios; raw.c_lflag &= ~(ECHO | ICANON); /* turn off ECHO and CANONICAL mode*/ tcsetattr(fd,TCSAFLUSH,&raw); /* apply new settings immediately */ } void restoreEchoMode(int fd, const struct termios* orig_termios){ tcsetattr(fd,TCSAFLUSH,orig_termios); /* restore original terminal attrs */ } int main(){ struct termios stored_settings; printf("Enter password:"); fflush(stdout); disableEchoMode(STDIN_FILENO, &stored_settings); char passwrd[BUFSIZ]; fgets(passwrd,sizeof(passwrd),stdin); restoreEchoMode(STDIN_FILENO, &stored_settings); puts(""); printf("You entered:%s\n",passwrd); return 0; } ``` 这段代码首先保存了原始的终端参数,接着更改这些参数以移除回显标志位(`ECHO`)以及取消缓冲区满才发送数据的要求(`ICANON`)。最后,在完成操作后再次设置了原有的状态确保后续交互恢复正常[^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值