CppSecurity 1.1.2.0
C++ Security Library
Loading...
Searching...
No Matches
password_hashing_bcrypt.cpp
Go to the documentation of this file.
1
10
11#include "errors/exceptions.h"
12
13#include <libbcrypt.h>
14
15namespace CppSecurity {
16
17std::string BcryptPasswordHashing::_name = "bcrypt";
18
20 : PasswordHashing(64, 64),
21 _workfactor(workfactor)
22{
23}
24
26{
27 std::string salt(salt_length(), 0);
28 if (bcrypt_gensalt((int)workfactor(), salt.data()) != 0)
29 throwex CppCommon::SecurityException("Cannot generate 'bcrypt' salt!");
30 return salt;
31}
32
33std::string BcryptPasswordHashing::GenerateHash(std::string_view password, std::string_view salt) const
34{
35 // Generate the strong password hash
36 std::string hash(hash_length(), 0);
37 if (bcrypt_hashpw(password.data(), salt.data(), hash.data()) != 0)
38 throwex CppCommon::SecurityException("Cannot generate 'bcrypt' hash!");
39 return hash;
40}
41
42std::string BcryptPasswordHashing::GenerateDigest(std::string_view password) const
43{
44 std::string salt = GenerateSalt();
45 return GenerateHash(password, salt);
46}
47
48bool BcryptPasswordHashing::Validate(std::string_view password, std::string_view hash, std::string_view salt) const
49{
50 // Calculate the digest for the given password and salt
51 std::string digest(hash.size(), 0);
52 if (bcrypt_hashpw(password.data(), salt.data(), digest.data()) != 0)
53 throwex CppCommon::SecurityException("Cannot calculate 'bcrypt' hash!");
54
55 // Compare the digest with the given hash
56 return (digest == hash);
57}
58
59bool BcryptPasswordHashing::ValidateDigest(std::string_view password, std::string_view digest) const
60{
61 // Check the digest size (must be hash + salt)
62 if (digest.size() != hash_length())
63 return false;
64
65 // Perform the password validation
66 return (bcrypt_checkpw(password.data(), digest.data()) == 0);
67}
68
69} // namespace CppSecurity
bool ValidateDigest(std::string_view password, std::string_view digest) const override
Validate the user password over the given secure digest string.
std::string GenerateDigest(std::string_view password) const override
Generate the secure digest string for the given user password.
std::string GenerateHash(std::string_view password, std::string_view salt) const override
Generate the strong password hash for the given user password and unique salt.
std::string GenerateSalt() const override
Generate the unique password salt.
bool Validate(std::string_view password, std::string_view hash, std::string_view salt) const override
Validate the user password over the given strong password hash and unique salt.
size_t workfactor() const noexcept
Get the work factor.
BcryptPasswordHashing(size_t workfactor=4)
Initialize 'bcrypt' password hashing with required parameters.
Password hashing interface.
size_t salt_length() const noexcept
Get the unique password salt length.
size_t hash_length() const noexcept
Get the strong password hash length.
'bcrypt' password hashing algorithm definition