NAWA 0.9
Web Application Framework for C++
BcryptHashingEngine.cpp
Go to the documentation of this file.
1/*
2 * Copyright (C) 2019-2022 Tobias Flaig.
3 *
4 * This file is part of nawa.
5 *
6 * nawa is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Lesser General Public License,
8 * version 3, as published by the Free Software Foundation.
9 *
10 * nawa is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public License
16 * along with nawa. If not, see <https://www.gnu.org/licenses/>.
17 */
18
24#include <cstring>
25#include <libbcrypt/bcrypt.h>
26#include <nawa/Exception.h>
28
29using namespace nawa;
30using namespace std;
31
32struct hashing::BcryptHashingEngine::Data {
33 int workFactor;
34 string salt;
35
36 Data(int workFactor, string salt) : workFactor(workFactor), salt(std::move(salt)) {}
37};
38
39NAWA_DEFAULT_DESTRUCTOR_IMPL_WITH_NS(hashing, BcryptHashingEngine)
40
41hashing::BcryptHashingEngine::BcryptHashingEngine(int workFactor, std::string salt) {
42 data = make_unique<Data>(workFactor, std::move(salt));
43}
44
45std::string hashing::BcryptHashingEngine::generateHash(std::string input) const {
46 char bcsalt[BCRYPT_HASHSIZE];
47 char hash[BCRYPT_HASHSIZE];
48
49 // use the user-defined salt if necessary
50 if (!data->salt.empty()) {
51 string salt_res = data->salt;
52 salt_res.resize(BCRYPT_HASHSIZE, '\0');
53 memcpy(hash, salt_res.c_str(), BCRYPT_HASHSIZE);
54 } else if (bcrypt_gensalt(data->workFactor, bcsalt) != 0) {
55 throw Exception(__PRETTY_FUNCTION__, 10,
56 "Could not generate a salt (unknown bcrypt failure).");
57 }
58
59 if (bcrypt_hashpw(input.c_str(), bcsalt, hash) != 0) {
60 throw Exception(__PRETTY_FUNCTION__, 11,
61 "Could not hash this password (unknown bcrypt failure).");
62 }
63 return {hash, 60};
64}
65
66bool hashing::BcryptHashingEngine::verifyHash(std::string input, std::string hash) const {
67 // return value of bcrypt_checkpw is -1 on failure, 0 on match, and >0 if not matching
68 int ret = bcrypt_checkpw(input.c_str(), hash.c_str());
69 return ret == 0;
70}
Hashing engine for password hashing using Argon2.
Exception class that can be used by apps to catch errors resulting from nawa function calls.
bool verifyHash(std::string input, std::string hash) const override
#define NAWA_DEFAULT_DESTRUCTOR_IMPL_WITH_NS(Namespace, Class)
Definition: macros.h:37
Definition: AppInit.h:31