Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple password compare using crypt in C

I read the first password from the user and encrypted it. Then I read a second password and encrypted it. I then compared the two encrypted passwords, but the comparison always states they're equal. I narrowed the problem to this: After the second encryption, the password and guess variables have the same value. This is a strange error; can anyone provide insight and/or a fix?

Thank you in advance. The code:

int main(void)
{
  char salt[] = "00";
  char *password;
  char *guess;

  password = crypt(getpass("Enter Password1:"), salt);
  printf("password = %s\n", password);

  guess = crypt(getpass("Enter Password2:"), salt);
  printf("password = %s\n", password);
  printf("guess = %s\n", guess);

  puts(strcmp(guess, password) == 0
       ? "Access Granted." : "Access Denied.");

  return 0;
}

The output:

Enter Password1:
password = 007XN7q4UF/o6
Enter Password2:
password = 00MqrTyK65aEA
guess = 00MqrTyK65aEA
Access Granted.
like image 969
Noah Avatar asked Jan 15 '23 01:01

Noah


1 Answers

According to the manpage for crypt, it returns a pointer to a static buffer.

You'll have to copy both guess and password:

password = strdup(crypt(getpass("Enter Password1:"), salt));
...
guess = strdup(crypt(getpass("Enter Password2:"), salt));
like image 192
ldav1s Avatar answered Jan 26 '23 06:01

ldav1s