CppSecurity  1.1.1.0
C++ Security Library
password_hashing_scrypt.cpp
Go to the documentation of this file.
1 
10 
11 #include "errors/exceptions.h"
12 
13 #include <libscrypt.h>
14 
15 namespace CppSecurity {
16 
17 std::string ScryptPasswordHashing::_name = "scrypt";
18 
19 ScryptPasswordHashing::ScryptPasswordHashing(size_t hash_length, size_t salt_length, uint64_t n, uint32_t r, uint32_t p)
20  : PasswordHashing(hash_length, salt_length),
21  _n(n), _r(r), _p(p)
22 {
23 }
24 
25 std::string ScryptPasswordHashing::GenerateHash(std::string_view password, std::string_view salt) const
26 {
27  // Generate the strong password hash
28  std::string hash(hash_length(), 0);
29  if (libscrypt_scrypt((const uint8_t*)password.data(), password.size(), (const uint8_t*)salt.data(), salt.size(), n(), r(), p(), (uint8_t*)hash.data(), hash.size()) != 0)
30  throwex CppCommon::SecurityException("Cannot generate 'scrypt' hash!");
31  return hash;
32 }
33 
34 bool ScryptPasswordHashing::Validate(std::string_view password, std::string_view hash, std::string_view salt) const
35 {
36  // Calculate the digest for the given password and salt
37  std::string digest(hash.size(), 0);
38  if (libscrypt_scrypt((const uint8_t*)password.data(), password.size(), (const uint8_t*)salt.data(), salt.size(), n(), r(), p(), (uint8_t*)digest.data(), digest.size()) != 0)
39  throwex CppCommon::SecurityException("Cannot calculate 'scrypt' hash!");
40 
41  // Compare the digest with the given hash
42  return (digest == hash);
43 }
44 
45 } // namespace CppSecurity
Password hashing interface.
size_t hash_length() const noexcept
Get the strong password hash length.
uint32_t r() const noexcept
Get the RAM Cost.
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.
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.
ScryptPasswordHashing(size_t hash_length=32, size_t salt_length=32, uint64_t n=512, uint32_t r=8, uint32_t p=1)
Initialize 'scrypt' password hashing with required parameters.
uint32_t p() const noexcept
Get the degree of parallelism.
uint64_t n() const noexcept
Get the CPU AND RAM cost.
'scrypt' password hashing algorithm definition