C Password Program

tux4life 0 Tallied Votes 8K Views Share

One of the things which attracted my attention was that there are often newbies asking how to create a password program in C/C++, often they don't succeed, well here's my response, you can use it for any purpose you want, one thing you'll have to keep in mind is that this code will only work on compilers which support conio.h, I know that it's actually a bad habit to make use of this "library", but most of the newbies which are searching for code like this are always using a compiler which supports it, so I guess that won't be a big problem.
As compiler to compile this code I used MinGW.
(The world's best open source compiler for Windows)
You can get the command line compiler from the site, however if you're new to
C/C++ then I would rather suggest you to go and get an IDE featuring the MinGW compiler: Code::Blocks is a very good one, also often used is the Dev-C++ IDE, but there's on major disadvantage of Dev-C++: The source code editor of the IDE isn't being updated anymore (however you can still use it with the newest MinGW compiler, that would be no problem)

#include <stdio.h>
#include <string.h>
#include <conio.h>

int main()
{
    char buffer[256] = {0};
    char password[] = "password";
    char c;
    int pos = 0;
    
    printf("%s", "Enter password: ");
    do {
        c = getch();
        
        if( isprint(c) ) 
        {
            buffer[ pos++ ] = c;
            printf("%c", '*');
        }
        else if( c == 8 && pos )
        {
            buffer[ pos-- ] = '\0';
            printf("%s", "\b \b");
        }
    } while( c != 13 );
    
    if( !strcmp(buffer, password) )
        printf("\n%s\n", "Logged on succesfully!");
    else
        printf("\n%s\n", "Incorrect login!");

    return 0;
}
tux4life 2,072 Postaholic

Bug Fix!
Change: buffer[ pos[B]--[/B] ] = '\0'; to: buffer[ [B]--[/B]pos ] = '\0'; :)

tux4life 2,072 Postaholic

Code Improvement!
It might be a good practice to change the loop's condition,
from: while( c != 13 ); to: while( c != 13 && pos < 256); as this will avoid to go over the bounds of the buffer.
:)

Asafe 0 Newbie Poster

If you pretend this to be valid C++ totally FAIL.

tux4life 2,072 Postaholic

>If you pretend this to be valid C++ totally FAIL.
Well, in fact this is all valid C++, with the minor exception that I used an unportable library, but does that make it invalid C++ code?
The code is not standard C++ (but that's only because I used the conio library).
BTW, I posted this snippet in the C section of code snippets and not in the C++ section, but it should work on most C++ compilers as well (as long as they support conio.h).
When you intend to compile this code on a C++ compiler, then you should of course change the include directives to include the new-style headers, because most compilers only provide the old-style headers for backwards compatibility and because therefore they're not standard.
And if you want, you can always use the C++ iostream class library for I/O.
But remember that my intention was that it is C code in the first place.
Well, I would like to see you how you would do it in Standard (valid) C++.

superdav42 0 Newbie Poster

In case you didn't know this isn't very secure. It is possible to find the hard coded password simply by analyzing the compiled binary file. Like so: cat password gives something like:

US=u@-X9sB9r[]Ív'Utt	$ÐL$qUWQ0DžrDž@DžpassDžwordƅED$P$aUE}`~&}z UuD$$)uD$h$D$$0Y_]aÐU]Ít&'UWVSO

it not as plain as day but you can see the hard coded password there. Using a hex editor it would be even easier to read it.

If you want real security it needs to be encrypted using sha1 or some other scheme.

tux4life 2,072 Postaholic

First of all: my intention was to write a program which just lets the user enter a password, while displaying an asterisk for each character entered (correction through backspace allowed).

However you're right in saying that this program is not secure, because the password is hardcoded, but it was never my intention that my program would be used as it's displayed here for 'serious' programs.
I included a variable, which contains a hardcoded password, with the only purpose to be able to demonstrate this little program.

People here are free to copy my code and modify it according to their needs, if they want to enhance security by using hashed passwords, that's okay.

Using hashing, you'll have to do something like this in general:

  1. Get the hashed password.
  2. Get the user entered password.
  3. Hash the password entered by the user and compare it to the hashed (correct) password.
    If the comparison yields true, then log the user in.
Kenclozand3 0 Newbie Poster

it helps me, thank you

Noel Malle 0 Newbie Poster

It help but you must include header file ctype.h

yashsaxena -1 Light Poster

Hey nice password program.
I did not tried this before.
but i want that when user inputs the password then user must see * instead of actual chars.
How can I? :P

vedro-compota commented: +++ +3
aravindanne 0 Newbie Poster

Thanks for the above program
now i am safe with my programs
thank you very much for the owner
if you need any help contact me...<snipped>

Adytzu04 0 Newbie Poster

Hy! I'm sorry that i revive this topic but i have a problem with this code! I added a do{ } while so that i can reenter the password again if it's typed incorrect.Now if i type the password correctly for the first time it works, but if i typed wrong then correct it sais that the password is wrong. Why?

#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <ctype.h>

int main()
{
char buffer[256] = {0};
char password[] = "password";
char c;
int pos = 0,k=0;

do{           //start 
printf("%s", "Enter password: ");

do {
    c = getch();
    if( isprint(c) )
{
    buffer[ pos++ ] = c;
    printf("%c", '*');
}

else if( c == 8 && pos )

{
    buffer[ --pos ] = '\0';
    printf("%s", "\b \b");
}

} while( c != 13 && pos < 256);

if( !strcmp(buffer, password) )

{   k=1;
    printf("\n%s\n", "Logged on succesfully!");

}
else

{   printf("\n%s\n", "Incorrect login!");
    k=0;
}

} while(k==0);

return 0;

}
WaltP 2,905 Posting Sage w/ dash of thyme Team Colleague

Reformat your code so we can tell wht statements go with what DO loop.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

After lie 13 set pos = 0

Adytzu04 0 Newbie Poster

thx for answers! I've been able to make it work by making it into a function then accesing it from main with a loop

nilsonneto 0 Newbie Poster

Thank you!!
You've helped me so much!

np complete 8 Newbie Poster

Here we used getch() which is not standard. How should I code without using getch() ?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Here we used getch() which is not standard. How should I code without using getch() ?

There's no standard way to simulate getch(). Pick your favorite non-standard option to replace it.

Ab000dy_85 -3 Junior Poster in Training

you could use

cin.read(c, ONE_BYTE_LENGTH_CONST );

or hard code it to

cin.read(c, 1);

I did not try it if it could have a bug or so, just so you know/try.

WaltP 2,905 Posting Sage w/ dash of thyme Team Colleague

I did not try it if it could have a bug or so

So code it and see how miserably it fails to do the job... 8-|

Perla_1 0 Newbie Poster

wow.. nice password program.........
can u say meaning of this statement: printf("%s", "\b \b");

Assembly Guy 72 Posting Whiz

It could be simplified to printf("\b \b");. What it does it is prints a backspace character to the screen, thus moving the text cursor to the left one place. Then it prints a space, clearing whatever character was there before, and then prints another backspace character. It effectively means that whatever character was typed on the screen is removed from sight.

BNF 0 Newbie Poster

Yeah anytime you encourage newbie programmers to use some code you should mention any security risks you're aware of. You should do that at the same time that you introduce the code.

As you already discussed in earlier comments (so I know you understand this, mvmalderen), this part assumes the program knows the actual password:

if( !strcmp(buffer, password)

Any program handling passwords should never remember actual passwords. Instead they should remember a transformation of the password that cannot be reversed. Then anytime a user types their password, you do the same transformation on their input and compare that to what you have stored.

I've never implemented password storage so I don't know the specifics, but this seems like a good article to learn more:

http://www.codinghorror.com/blog/2007/09/youre-probably-storing-passwords-incorrectly.html

(Paying special attention to the quote from the cryptogtapher and the list of 4 things at the end. But I wouldn't take this single source as gospel either. Do some research.)

Anyway this is a cool piece of code, nice work!

usamaasghar.asghar 0 Newbie Poster

Well done :)

nonlinearly 0 Newbie Poster

I compliled it in Code::Blocks with Gnu GCC compiler only with <stdio.h> without problem (errors 0, warnings 0)... what a hell...

Remy1990 0 Newbie Poster

Thx for this, you helped me alot, keep up the good work!!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.