I have a class that takes user input (username/password), bcrypt hashes the input password to check if it matches the hash stored in the database, and then logs the user in if successful. The problem I'm experiencing is that if I call cout << "\n"
or sleep(1)
before hashing, the password check works as expected, but if I comment out sleep
and cout
, the hasher always fails, which results in the user getting an incorrect invalid credentials
message.
I'm using pqxx to read the database, and rg3's bcrypt to hash / check the passwords.
Code snippet where I first found the problem:
// pqxx::result
string storedPass = result.begin()["passwordBCrypt_12"].as<string>();
// Uncommenting either cout or sleep causes checkPassword to work as expected
//cout << "\n"; // Confusingly, cout must contain "\n" to have the effect
//sleep(1);
if (!checkPassword(inputPass, storedPass))
credError = true;
Code for checkPassword()
:
bool DB::checkPassword(string& password, string& passwordHash){
char cpassword[password.length()];
char hashInDatabase[BCRYPT_HASHSIZE];
char outTestHash[BCRYPT_HASHSIZE];
for (size_t i = 0; i < password.length(); i++){
cpassword[i] = password[i];
}
for (size_t i = 0; i < BCRYPT_HASHSIZE; i++){
hashInDatabase[i] = passwordHash[i];
}
if (bcrypt_hashpw(cpassword, hashInDatabase, outTestHash) == 0){
if (strcmp(hashInDatabase, outTestHash) == 0) {
// password matches
return true;
}
// password does not match
}
return false;
}
String inputPass
from the first code snippet is not handed down as a reference from other threads; it is copied.