NAWA  0.8
Web Application Framework for C++
BcryptHashingEngine.cpp
Go to the documentation of this file.
1 
6 /*
7  * Copyright (C) 2019-2021 Tobias Flaig.
8  *
9  * This file is part of nawa.
10  *
11  * nawa is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU Lesser General Public License,
13  * version 3, as published by the Free Software Foundation.
14  *
15  * nawa is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with nawa. If not, see <https://www.gnu.org/licenses/>.
22  */
23 
24 #include <cstring>
25 #include <libbcrypt/bcrypt.h>
26 #include <nawa/Exception.h>
28 
29 using namespace nawa;
30 using namespace std;
31 
32 struct hashing::BcryptHashingEngine::Data {
33  int workFactor;
34  string salt;
35 
36  Data(int workFactor, string salt) : workFactor(workFactor), salt(move(salt)) {}
37 };
38 
39 NAWA_DEFAULT_DESTRUCTOR_IMPL_WITH_NS(hashing, BcryptHashingEngine)
40 
41 hashing::BcryptHashingEngine::BcryptHashingEngine(int workFactor, string salt) {
42  data = make_unique<Data>(workFactor, move(salt));
43 }
44 
45 string hashing::BcryptHashingEngine::generateHash(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 string(hash, 60);
64 }
65 
66 bool hashing::BcryptHashingEngine::verifyHash(string input, 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
std::string generateHash(std::string input) const override
#define NAWA_DEFAULT_DESTRUCTOR_IMPL_WITH_NS(Namespace, Class)
Definition: macros.h:37
Definition: AppInit.h:31