歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux下用C語言來模擬密碼輸入

Linux下用C語言來模擬密碼輸入

日期:2017/3/1 10:03:15   编辑:Linux編程

以前在Linux環境下,想輸入密碼(關閉回顯)時都是用getpass函數,今天無意中看到手冊上說:This function is obsolete. Do not use it.

那我就自己實現一個類似的功能吧(功能相同,原理不同)

程序的思路很簡單:關閉回顯,讀取輸入,恢復設置。

上代碼:

#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <string.h>

#define MAXLEN 256

//參數dest是目標字符串, maxlen是最大長度,
//如果輸入超過了最大長度,則密碼將會被截斷
//成功返回0,否則返回-1
int new_getpass(char *dest, int maxlen)
{
struct termios oldflags, newflags;
int len;

//設置終端為不回顯模式
tcgetattr(fileno(stdin), &oldflags);
newflags = oldflags;
newflags.c_lflag &= ~ECHO;
newflags.c_lflag |= ECHONL;
if (tcsetattr(fileno(stdin), TCSANOW, &newflags) != 0)
{
perror("tcsetattr");
return -1;
}

//獲取來自鍵盤的輸入
fgets(dest, maxlen, stdin);
len = strlen(dest);
if( len > maxlen-1 )
len = maxlen - 1;
dest[len-1] = 0;

//恢復原來的終端設置
if (tcsetattr(fileno(stdin), TCSANOW, &oldflags) != 0)
{
perror("tcsetattr");
return -1;
}
return 0;
}

int main()
{
char password[MAXLEN];
printf("Enter password: ");
new_getpass(password, MAXLEN);
printf("You password is: %s\n", password);
return 0;
}

Copyright © Linux教程網 All Rights Reserved