打架和睡觉会导致不同的结果

cout and sleep cause different results

本文关键字:结果 打架      更新时间:2023-10-16

我有一个接受用户输入(用户名/密码)的类,bcrypt对输入密码进行哈希,以检查它是否与存储在数据库中的哈希相匹配,如果成功,则登录用户。我遇到的问题是如果我调用    cout << "n",,,,去,,,,sleep(1)     在哈希之前,密码检查按预期工作,但如果我注释掉sleepcout,哈希器总是失败,这导致用户得到错误的invalid credentials消息。

我使用pqxx来读取数据库,使用rg3的bcrypt来散列/检查密码。

第一次发现问题的代码片段:

// 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;


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;
}

字符串inputPass从第一个代码片段没有传递给其他线程作为引用;

正如评论中提到的,你有一个同步问题。

根据经验,只要sleep或cout(或printf)解决了你的问题,那么你就没有在程序的某些语句中正确地实现互斥逻辑。

您考虑纠正checkPassword函数。您100%确定存储传递的方式不需要某种同步吗?

PS:令人困惑的"n"效果有刷新缓冲区的习惯,导致同步。