Accepting Passwords from stdin
28 04 2008
I sometimes write small command line utilities that require a password. They are usually written in C++ for portability to other operating systems. Keep in mind that these snippets are only a "it-compiles-for-me" release, so don't hold me responsible for bugs you encounter.
In Xcode 3 (Mac OS X 10.5), I use the following code.
In Visual Studio 2003 and Bloodshed Dev-C++ (Windows XP SP2), I use the following code.
In Xcode 3 (Mac OS X 10.5), I use the following code.
#include <pwd.h>
#include <unistd.h>
#include <stdio.h>
static char * password;
int main (int argc, char * const argv[])
{
password = getpass("Enter Password: ");
printf("Password: %s\n", password);
return 0;
}
In Visual Studio 2003 and Bloodshed Dev-C++ (Windows XP SP2), I use the following code.
#include <cstdlib>
#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
using namespace std;
char * promptForPassword();
int main(int argc, char *argv[])
{
// Get and display the password
char * pw = promptForPassword();
printf("Password: %s\n", pw);
delete [] pw;
return 0;
}
char * promptForPassword()
{
char * pw = new char[1024]; // allow for password to have a maximum size of a kilobyte (could be handled dynamically by mallocing, strcpyring, freeing)
int i = 0;
char ch;
// Display the prompt
printf("Enter Password: ");
// Handle input
do
{
_flushall();
fflush(stdin);
ch = _getch();
switch (ch)
{
// If new character is the return key, just ignore and end the loop
case '\r':
break;
// If new character is the null char, ignore it
case '\0':
break;
// If new character is the backspace key, clean up the stdout and pw string
case '\010':
if (i > 0 && i <=1024)
{
cout<<"\010 \010"; // push the input marker back one character, overwrite the last character with a space, push input marker back
i--;
pw[i] = '\0';
}
break;
// Otherwise, append character to the string where possible
default:
if (i >= 0 && i < 1024)
{
pw[i] = ch;
cout<<'*';
i++;
}
break;
}
} while(ch != '\r');
pw[i] = '\0';
// After the user hits enter to end the password prompt, display a new line
printf("\n");
return pw;
}
My promptForPassword() function displays asterisk characters instead of input.
Of course, it is possible to combine the getpass() function from pwd.h into promptForPassword() by using #ifdef directives, so that the code would compile in all three IDEs (and all three compilers: Xcode uses gcc, Visual Studio uses Microsoft's compiler (I forget what they call it), and Dev-C++ uses mingw).
Categories : Programming
Trackbacks : No Trackbacks »

Trackbacks
No Trackbacks