LINUX:C言語でパスワード入力をシミュレート

1145 ワード

以前は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
", password); return 0; }