-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathpassword_hashing.cpp
77 lines (62 loc) · 2.32 KB
/
password_hashing.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*!
\file password_hashing.cpp
\brief Password hashing interface implementation
\author Ivan Shynkarenka
\date 04.06.2019
\copyright MIT License
*/
#include "security/password_hashing.h"
#include "errors/exceptions.h"
#include "memory/memory.h"
#include "string/encoding.h"
#include <cassert>
namespace CppSecurity {
PasswordHashing::PasswordHashing(size_t hash_length, size_t salt_length)
: _hash_length(hash_length), _salt_length(salt_length)
{
assert((hash_length >= 8) && "Hash length should be at least 8 bytes!");
if (hash_length < 8)
throwex CppCommon::SecurityException("Invalid hash length!");
assert((salt_length >= 8) && "Salt length should be at least 8 bytes!");
if (salt_length < 8)
throwex CppCommon::SecurityException("Invalid salt length!");
}
std::string PasswordHashing::GenerateSalt() const
{
std::string salt(salt_length(), 0);
CppCommon::Memory::CryptoFill(salt.data(), salt.size());
return salt;
}
std::pair<std::string, std::string> PasswordHashing::GenerateHashAndSalt(std::string_view password) const
{
std::string salt = GenerateSalt();
std::string hash = GenerateHash(password, salt);
return std::make_pair(hash, salt);
}
std::string PasswordHashing::GenerateDigest(std::string_view password) const
{
auto digest = GenerateHashAndSalt(password);
return digest.first + digest.second;
}
std::string PasswordHashing::GenerateEncodedDigest(std::string_view password) const
{
// Encode the digest into the Base64 encoding
return CppCommon::Encoding::Base64Encode(GenerateDigest(password));
}
bool PasswordHashing::ValidateDigest(std::string_view password, std::string_view digest) const
{
// Check the digest size (must be hash + salt)
if (digest.size() != (hash_length() + salt_length()))
return false;
// Extract hash and salt from the digest
std::string_view hash(digest.data(), hash_length());
std::string_view salt(digest.data() + hash_length(), salt_length());
// Perform the password validation
return Validate(password, hash, salt);
}
bool PasswordHashing::ValidateEncodedDigest(std::string_view password, std::string_view digest) const
{
// Decode the digest from the Base64 encoding
return ValidateDigest(password, CppCommon::Encoding::Base64Decode(digest));
}
} // namespace CppSecurity