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