The Battle for Wesnoth  1.17.0-dev
auth.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2015 - 2021
3  by Iris Morelle <shadowm2006@gmail.com>
4  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
5 
6  This program is free software; you can redistribute it and/or modify
7  it under the terms of the GNU General Public License as published by
8  the Free Software Foundation; either version 2 of the License, or
9  (at your option) any later version.
10  This program is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY.
12 
13  See the COPYING file for more details.
14 */
15 
17 
18 #include "hash.hpp"
19 #include "serialization/base64.hpp"
20 
21 #include <ctime>
22 #include <boost/random.hpp>
23 #include <boost/generator_iterator.hpp>
24 
25 namespace campaignd
26 {
27 
28 namespace auth
29 {
30 
31 namespace
32 {
33 
34 std::string generate_salt(std::size_t len)
35 {
36  boost::mt19937 mt(std::time(0));
37  auto salt = std::string(len, '0');
38  boost::uniform_int<> from_str(0, 63); // 64 possible values for base64
39  boost::variate_generator< boost::mt19937, boost::uniform_int<>> get_char(mt, from_str);
40 
41  for(std::size_t i = 0; i < len; i++) {
42  salt[i] = crypt64::encode(get_char());
43  }
44 
45  return salt;
46 }
47 
48 } // end unnamed namespace
49 
50 bool verify_passphrase(const std::string& passphrase, const std::string& salt, const std::string& hash)
51 {
52  return utils::md5(passphrase, salt).base64_digest() == hash;
53 }
54 
55 std::pair<std::string, std::string> generate_hash(const std::string& passphrase)
56 {
57  const auto& salt = generate_salt(16);
58  return { salt, utils::md5(passphrase, salt).base64_digest() };
59 }
60 
61 } // end namespace auth
62 
63 } // end namespace campaignd
campaignd authentication API.
virtual std::string base64_digest() const override
Definition: hash.cpp:122
std::string encode(utils::byte_string_view bytes)
Definition: base64.cpp:230
std::pair< std::string, std::string > generate_hash(const std::string &passphrase)
Generates a salted hash from the specified passphrase.
Definition: auth.cpp:55
std::size_t i
Definition: function.cpp:967
bool verify_passphrase(const std::string &passphrase, const std::string &salt, const std::string &hash)
Verifies the specified plain text passphrase against a salted hash.
Definition: auth.cpp:50