0

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.

Ed79
  • 3
  • 3

3 Answers3

3

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.

Community
  • 1
  • 1
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0
int issymbol(int password)

Your variable password should be char type to check symbols instead of int.

Edit:

scanf("%s", password);

Always put space before %s, like

scanf(" %s", password)

This will terminate all previous \n.

Tommac1
  • 11
  • 5
  • Should i also put " %6s". – Ed79 Aug 12 '16 at 11:00
  • Nope: the password is the first thing the user types. The leading space is a crude, but occasionally effective, way of passing over the newline character that's sent to the input buffer when the user types return. – Bathsheba Aug 12 '16 at 11:03
0

The problem is that you're checking more characters than you typed. If you type SS7, there are only 3 characters to check, but your for loop checks all 7 characters in password. The characters after password[3] will be uninitialized, and they might contain characters that meet the requirements.

Change the loop to:

for (i = 0; password[i]; i++) {

This will stop when it reaches the terminating null character in the string.

Barmar
  • 741,623
  • 53
  • 500
  • 612