CppSecurity 1.1.2.0
C++ Security Library
Loading...
Searching...
No Matches
password_hashing_pbkdf2.cpp
Go to the documentation of this file.
1
10
11#include <openssl/evp.h>
12
13namespace CppSecurity {
14
15std::string PBKDF2PasswordHashing::_name = "PBKDF2";
16
17PBKDF2PasswordHashing::PBKDF2PasswordHashing(size_t hash_length, size_t salt_length, PBKDF2 algorithm, size_t iterations)
18 : PasswordHashing(hash_length, salt_length),
19 _algorithm(algorithm),
20 _iterations(iterations)
21{
22}
23
24std::string PBKDF2PasswordHashing::GenerateHash(std::string_view password, std::string_view salt) const
25{
26 // Generate the strong password hash
27 const EVP_MD* md = nullptr;
28 std::string hash(hash_length(), 0);
29 switch (algorithm())
30 {
32 md = EVP_sha1();
33 break;
35 md = EVP_sha256();
36 break;
38 md = EVP_sha512();
39 break;
40 }
41 if (PKCS5_PBKDF2_HMAC((const char*)password.data(), (int)password.size(), (const uint8_t*)salt.data(), (int)salt.size(), (int)iterations(), md, (int)hash.size(), (uint8_t*)hash.data()) == 0)
42 throwex CppCommon::SecurityException("Cannot generate 'PBKDF2' hash!");
43 return hash;
44}
45
46bool PBKDF2PasswordHashing::Validate(std::string_view password, std::string_view hash, std::string_view salt) const
47{
48 // Calculate the digest for the given password and salt
49 const EVP_MD* md = nullptr;
50 std::string digest(hash.size(), 0);
51 switch (algorithm())
52 {
54 md = EVP_sha1();
55 break;
57 md = EVP_sha256();
58 break;
60 md = EVP_sha512();
61 break;
62 }
63 if (PKCS5_PBKDF2_HMAC((const char*)password.data(), (int)password.size(), (const uint8_t*)salt.data(), (int)salt.size(), (int)iterations(), md, (int)digest.size(), (uint8_t*)digest.data()) == 0)
64 throwex CppCommon::SecurityException("Cannot calculate 'PBKDF2' hash!");
65
66 // Compare the digest with the given hash
67 return (digest == hash);
68}
69
70} // namespace CppSecurity
PBKDF2PasswordHashing(size_t hash_length=32, size_t salt_length=32, PBKDF2 algorithm=PBKDF2::HMAC_SHA512, size_t iterations=1000)
Initialize 'PBKDF2' password hashing with required parameters.
size_t iterations() const noexcept
Get the count of 'PBKDF2' iterations.
PBKDF2 algorithm() const noexcept
Get the 'PBKDF2' algorithm.
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.
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.
Password hashing interface.
size_t hash_length() const noexcept
Get the strong password hash length.
PBKDF2
'PBKDF2' algorithm
@ HMAC_SHA1
HMAC-SHA1.
@ HMAC_SHA256
HMAC-SHA256.
@ HMAC_SHA512
HMAC-SHA512.
'PBKDF2' password hashing algorithm definition