R-Type
Distributed multiplayer game engine in C++
Loading...
Searching...
No Matches
Argon2PasswordHasher.cpp
Go to the documentation of this file.
1/*
2** EPITECH PROJECT, 2025
3** r-type
4** File description:
5** Argon2PasswordHasher - Argon2id password hashing implementation
6*/
7
9#include <argon2.h>
10#include <random>
11#include <stdexcept>
12
14 : _timeCost(2), _memoryCost(65536), _parallelism(1), _hashLength(32), _saltLength(16) {}
15
16Argon2PasswordHasher::Argon2PasswordHasher(uint32_t timeCost, uint32_t memoryCost, uint32_t parallelism,
17 size_t hashLength, size_t saltLength)
18 : _timeCost(timeCost),
19 _memoryCost(memoryCost),
20 _parallelism(parallelism),
21 _hashLength(hashLength),
22 _saltLength(saltLength) {}
23
24std::string Argon2PasswordHasher::hash(const std::string &password) {
25 if (password.empty()) {
26 throw std::invalid_argument("Password cannot be empty");
27 }
28
29 // Generate random salt
30 std::vector<unsigned char> salt(_saltLength);
31 std::random_device rd;
32 std::mt19937 gen(rd());
33 std::uniform_int_distribution<> dis(0, 255);
34 for (size_t i = 0; i < _saltLength; ++i) {
35 salt[i] = static_cast<unsigned char>(dis(gen));
36 }
37
38 // Allocate buffer for encoded hash
39 const size_t encodedLength = 128;
40 std::vector<char> encoded(encodedLength);
41
42 // Hash password using Argon2id
43 int result =
44 argon2id_hash_encoded(_timeCost, _memoryCost, _parallelism, password.c_str(), password.length(),
45 salt.data(), _saltLength, _hashLength, encoded.data(), encodedLength);
46
47 if (result != ARGON2_OK) {
48 throw std::runtime_error(std::string("Argon2 hashing failed: ") + argon2_error_message(result));
49 }
50
51 return std::string(encoded.data());
52}
53
54bool Argon2PasswordHasher::verify(const std::string &password, const std::string &hash) {
55 if (password.empty() || hash.empty()) {
56 return false;
57 }
58
59 // Verify password against Argon2id hash
60 int result = argon2id_verify(hash.c_str(), password.c_str(), password.length());
61
62 return result == ARGON2_OK;
63}
std::string hash(const std::string &password) override
Hash a plaintext password using Argon2id.
bool verify(const std::string &password, const std::string &hash) override
Verify a password against an Argon2id hash.
Argon2PasswordHasher()
Constructor with default parameters.