Wednesday, July 4, 2012

Scan Characters without echoing - C

Happy to see you again..!

Have you noticed in UNIX terminal.. ? The characters of password you are typing will be hidden, that is not even replaced with a dot or asterisk(*) else nothing will be displayed. So it's impossible to find the number of characters in the password. What we are
going to do is the same... But with a simple logic. Hope you know how getch() function which is defined in <conio.h>. It just receives a character and returns the same but without echoing and it'll not wait for return key. We are going to do a trick with this..! See the code below.

Code:


#include<stdio.h>
#include<string.h>
#ifdef __LINUX__
#include"myconio.h"  //get it from here
#elif 
#include<conio.h>
#endif
#define passwd()||linux_passwd() pwdio(char p[255],int c)
void main(void)
 {
  int i;
  char k[30];
  printf("\nEnter the Password:");
  gets(k);
  i=pwdio(k);
  if(i==0)
   {
    printf("\nPassword Accepted.");
   }
 else
  {
   printf("\nPassword Rejected.");
  }

pwdio(char *p,int *c=0)
 {
    int j,k;
    char pc[255];
    int disp;
    disp=c;
    for(j=0;j<255;j++)
     {
      pc[j]=getch();
      if(pc[j]==10) //ASCII of ENTER_KEY
       {
        pc[j]='\0';
        break;
       }
       if(disp!=0)
     {   printf("%c",c);
     
     if(pc[j]==127)
       {
        k=j;
        j=j-2;
        printf("\b\b\b");
     } 
        }
     }
   k=strcmp(p,pc);
   if(k==0)
   return 0;
 }

In the above code, the function pwdio(char*, int* =0) the getch() function is used inside a loop for getting variables. And I didn't follow any encryption here, because for easy understanding. Suppose if the input was like

i=pwdio(k,'*');


the typed characters will be displayed as *.. If you din't understand the code, feel free to ask for further explanation.

No comments:

Post a Comment