歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> Linux下接收用戶輸入密碼的完美實現

Linux下接收用戶輸入密碼的完美實現

日期:2017/2/28 17:35:21   编辑:Linux教程
一個小問題,在linux編一個接收用戶輸入密碼小程序,不顯示密碼。google和baidu了一下,竟然沒有找到現成的,好吧,自己編一個。哪裡想到,竟然一波三折。哈哈,最終還是搞定了!

1) 很容易根據termios的結構屏蔽終端屬性的輸出。
但是,這樣一來,用戶的輸入不顯示在屏幕上。用戶不知道自己輸入的個數。對輸入的內容心裡也沒有底。非常不方便。

2)於是改為一個一個字符的處理格式。編程實現了用'*'代替用戶的輸入。但是這樣linux處於非授權模式,一個限制是‘退格’鍵不能用。用戶必須保證一次輸入正確,萬一錯了的話,只能眼睜睜的重新運行程序,重來一次。

3)我最終在2)的基礎上,實現了用'*'代替用戶的輸入,並且backspace key可用。

附代碼:
#include
#include

#define passLength 100

int main(int argc, char **argv)
{
struct termio tio, tin;
char*password =(char*)malloc(passLength);
char*b=password;

ioctl(0, TCGETA, &tio);
tin = tio;
tin.c_lflag &= ~ECHO; /* turn off ECHO */
tin.c_lflag &= ~ICANON; /* turn off ICANON */
tin.c_lflag &= ~ISIG;
tin.c_cc[VINTR]=1;
tin.c_cc[VMIN]=1;
tin.c_cc[VTIME]=0;
/*
* Set the new modes. Again we ignore return
* values.
*/
ioctl(0,TCSETA,&tin);

char selected;
int order=0;
printf("Enter password:");
do{
selected =fgetc(stdin);
if((selected=='\b')&&(order>0))
{
fputc('\b',stdout);
fputc(' ',stdout);
fputc('\b',stdout);
order--;
password--;
*password='\0';
}else if((selected!='\n')&&(selected!='\r')&&(selected!='\b'){

*password++=selected;
order++;
fputc('*',stdout);
fflush(stdout);
}
}while ((selected!='\n')&&(selected!='\r')&&(order>=0)&&(order
/*
* Reset the old tty modes.
*/
ioctl(0, TCSETA, &tio);
fprintf(stdout,"\nYou entered: %s\n",b);
free(b);
exit(0);

}
Copyright © Linux教程網 All Rights Reserved