commonlib
bcrypt.h
Go to the documentation of this file.
1 
11 #pragma once
12 #include <string>
13 #include <random>
14 #include <stdexcept>
15 #include "crypto.h"
16 
17 BEGIN_NAMESPACE_CRYPTO
18 
22 class BCrypt
23 {
24 private:
25  static const int InfoPartSize = 7;
26  static const int SaltPartSize = 22;
27  static const int HashPartSize = 31;
28  static const int SaltSize = InfoPartSize + SaltPartSize;
29  static const int HashSize = InfoPartSize + SaltPartSize + HashPartSize;
30 
31  std::random_device randomDevice;
32  std::uniform_int_distribution<int> randomDist;
33 
34  std::vector<char> randBytes(unsigned int length);
35 
36 public:
37  BCrypt();
38 
47  std::string hash(const std::string& password, unsigned int rounds = 10);
48 
60  std::string hash(const std::string& password, std::string salt, unsigned int rounds = 10) const;
61 
69  static bool Verify(const std::string& hash, const std::string& password);
70 
79  std::string generateSalt(unsigned int size);
80 
90  std::string generateSalt(char* bytes, int size) const;
91 };
92 
93 class BCryptException : public std::runtime_error
94 {
95 public:
96  explicit BCryptException(const std::string& message);
97 };
98 
100 {
101 public:
102  explicit BCryptSaltSizeException(unsigned int minSaltSize);
103 };
104 
105 END_NAMESPACE_CRYPTO
std::string hash(const std::string &password, unsigned int rounds=10)
Compute BCrypt hash of a password using random salt.
Definition: bcrypt.h:99
Wrapper class for BCrypt password hashing algorithm.
Definition: bcrypt.h:22
Definition: bcrypt.h:93
std::string generateSalt(unsigned int size)
Generate a random salt string of the specified size.
static bool Verify(const std::string &hash, const std::string &password)
Verifies if the password matches a hash.