Ed79 Ed79 - 3 months ago 24
C Question

Password Checker in C

I wanted to build a simple program that checks whether the user entered a password with at least one uppercase letter, one number and one symbol. Then if true print "This is a strong password".
But, when I started testing it, if I enter a pass like SS2, It counts as an strong password...

int issymbol(int password) {
if (password >= 33 && password <= 47) return 1;
else if (password >= 58 && password <= 64) return 1;
else if (password >= 91 && password <= 96) return 1;
else if (password >= 123 && password <= 126) return 1;
else return 0;
}

int main()
{
char password[7];
int i;
int u, d, s; // u - uppercase character
// d - digit
u = d = s = 0; // s - symbol

scanf("%s", password);

for(i = 0; i < 7; i++) {
if ( isupper(password[i]) && (u == 0) )
u++;
if ( isdigit(password[i]) && (d == 0) )
d++;
if ( issymbol(password[i]) && (s == 0) ) // Checks if password[i] is a symbol
s++;
if ( (u + d + s) >= 3) {
printf("Your password is strong!\n");
break;
}
}

if ( (u + d + s) < 3) printf("Your password is weak:(\n");

return 0;
}


Any ideas for improving it is welcome.

Answer

Don't you mean if (u >= 1 && d >= 1 && s >= 1) for a strong password? Then you can drop the tedium of writing && (u == 0) etc.

Your current test is little more than a character count.

Also, your code is quite brittle: things will go awry if the user inputs more than 6 characters: remember to set one byte aside for the nul-terminator \0. As an absolute minimum, write scanf("%6s", password); and run your loop to the first \0 rather than 7. See How to prevent scanf causing a buffer overflow in C? for more details.