diff --git a/ComplaintBox.cpp b/ComplaintBox.cpp index 6abd894..446f019 100644 --- a/ComplaintBox.cpp +++ b/ComplaintBox.cpp @@ -1,4 +1,5 @@ #include "ComplaintBox.h" +#include "bcrypt/BCrypt.hpp" #include #include #include @@ -50,8 +51,13 @@ void ComplaintBox::registerUser(bool isAdmin) { cout << PURPLE << "Enter password: " << RESET; cin >> pass; + // Hashing the password using bcrypt + string hashedPassword = BCrypt::generateHash(pass); + string table = isAdmin ? "adminusers" : "users"; - string sql = "INSERT INTO " + table + " (username, password) VALUES ('" + uname + "', '" + pass + "');"; + string sql = "INSERT INTO " + table + " (username, password) VALUES ('" + uname + "', '" + hashedPassword + "');"; + + if (sqlite3_exec(db, sql.c_str(), 0, 0, &errMsg) != SQLITE_OK) { cout << RED << "Error: " << errMsg << RESET << endl; @@ -69,13 +75,21 @@ bool ComplaintBox::loginUser(bool isAdmin) { cin >> pass; string table = isAdmin ? "adminusers" : "users"; - string sql = "SELECT * FROM " + table + " WHERE username = '" + uname + "' AND password = '" + pass + "';"; - bool success = false; + string sql = "SELECT password FROM " + table + " WHERE username = '" + uname + "';"; + string storedHash; + bool found = false; + + sqlite3_exec(db, sql.c_str(), [](void *data, int argc, char **argv, char **) -> int { + if (argc > 0 && argv[0]) { + *((string*)data) = argv[0]; + return 0; + } + return 1; + }, &storedHash, &errMsg); + + // Validating password using bcrypt + bool success = BCrypt::validatePassword(pass, storedHash); - sqlite3_exec(db, sql.c_str(), [](void *successPtr, int, char **, char **) -> int { - *(bool*)successPtr = true; - return 0; - }, &success, &errMsg); if (success) { cout << GREEN << "Login successful!\n" << RESET; diff --git a/include/bcrypt/BCrypt.hpp b/include/bcrypt/BCrypt.hpp new file mode 100644 index 0000000..07e5c53 --- /dev/null +++ b/include/bcrypt/BCrypt.hpp @@ -0,0 +1,32 @@ +#ifndef __BCRYPT__ +#define __BCRYPT__ + +#ifdef _WIN32 +#include "winbcrypt.h" +#else + +#include "bcrypt.h" +#include +#include + +class BCrypt { +public: + static std::string generateHash(const std::string & password, int workload = 12){ + char salt[BCRYPT_HASHSIZE]; + char hash[BCRYPT_HASHSIZE]; + int ret; + ret = bcrypt_gensalt(workload, salt); + if(ret != 0)throw std::runtime_error{"bcrypt: can not generate salt"}; + ret = bcrypt_hashpw(password.c_str(), salt, hash); + if(ret != 0)throw std::runtime_error{"bcrypt: can not generate hash"}; + return std::string{hash}; + } + + static bool validatePassword(const std::string & password, const std::string & hash){ + return (bcrypt_checkpw(password.c_str(), hash.c_str()) == 0); + } +}; + +#endif + +#endif // __BCRYPT__ diff --git a/lib/bcrypt.lib b/lib/bcrypt.lib new file mode 100644 index 0000000..43b2186 Binary files /dev/null and b/lib/bcrypt.lib differ