Linux與Windows下實現密碼隱藏輸入方法

Linux 下實現:

  #include "termios.h"

  struct termios new_t, old_t;
  tcgetattr(0, &old_t);
  new_t = old_t; 
  new_t.c_lflag &= (~ICANON);    
  new_t.c_lflag &= (~ECHO);         
  new_t.c_cc[VTIME] = 0;
  new_t.c_cc[VMIN] = 1;
  tcsetattr(0, TCSANOW, &new_t);

 tcsetattr(0, TCSANOW, &old_t);

TC 下實現輸入變爲"*"號: 

#include <stdio.h>
 
int inputpw (char *password,int len); /*len爲密碼的最長長度*/
 
main (void)
{ int l;
 char pw[13];
 l=inputpw(pw,12);
 printf("/n剛纔輸入%d位的密碼:%s",l,pw);
 return 0;
}
 
int inputpw(char *password,int len) 
{
 int i=0; /*密碼數組索引值,同時也表示記錄已顯示星的數目,初始化值爲0*/
 char ch;
 printf("/n請輸入密碼(長度小於等於%d位): ",len);
 fflush(stdin); /*清洗流,以防妨礙密碼正確輸入*/
 for ( ch = getch(); ch!=13;ch = getch() ) /*若用戶輸入回車則結束密碼輸入*/ 
 {
 if (i>=len) continue; /*如果已到達len指定的長度則……*/
 
 if ( ch == 8 ) /*若用戶按了退格鍵則……*/
 {
 if ( i > 0 ) /*如果已顯示星數不爲0則……*/
 {
 printf("/b"); /*退一個格*/
 password[--i]='/0'; /*password[i-1]的值改爲'/0', 已顯示星數減一,數組索引值減一*/
 }
 putchar(0); /*顯示空字符*/
 printf("/b"); /*退一個格*/
 continue ;
 }
 
 if( ch<32 || ch>127 ) continue; /*密碼只能爲ASCII碼值爲32-127的字符*/
 
 printf("*"); /*上述情況都不是則顯示一個星*/
 password[i++]=ch; /*將ch賦給password[i],已顯示星數加一,數組索引值加一*/ 
 }
 password[i] = '/0'; /*設置結尾的空字符*/
 return i;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章