LINUX C实现密码输入不回显

原文: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.csdn.net/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"

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值