#include "auth.h" #include #include #include #include // crypt specified password std::string Auth::generate(const std::string& pw) { struct crypt_data data; memset((void *)&data, '\0', sizeof(data)); char setting[1000]; if (crypt_gensalt_rn("$6$", 2000, nullptr, 0, setting, sizeof(setting)) == nullptr) throw std::runtime_error("Error on crypt_gensalt_r()"); char* result; if ((result = crypt_r(pw.data(), setting, &data)) == nullptr) throw std::runtime_error("Error on crypt_r()"); return result; } // validate specified password against crypted hash bool Auth::validate(const std::string& crypted, const std::string& pw) { struct crypt_data data; memset((void *)&data, '\0', sizeof(data)); size_t pos = crypted.find_last_of('$'); if (pos == crypted.npos) { std::cerr << "Warning: Bad password hash configured (format)" << std::endl; return false; } std::string setting{crypted.substr(0, pos)}; char* output; if ((output = crypt_r(pw.data(), setting.data(), &data)) == nullptr) { std::cerr << "Warning: Error on crypt_r()" << std::endl; return false; } return crypted == output; }