]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/modules/hash.h
Merge pull request #677 from Robby-/master-dnsblzline
[user/henk/code/inspircd.git] / include / modules / hash.h
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2010 Daniel De Graaf <danieldg@inspircd.org>
5  *
6  * This file is part of InspIRCd.  InspIRCd is free software: you can
7  * redistribute it and/or modify it under the terms of the GNU General Public
8  * License as published by the Free Software Foundation, version 2.
9  *
10  * This program is distributed in the hope that it will be useful, but WITHOUT
11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
13  * details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18
19
20 #pragma once
21
22 #include "modules.h"
23
24 class HashProvider : public DataProvider
25 {
26  public:
27         const unsigned int out_size;
28         const unsigned int block_size;
29         HashProvider(Module* mod, const std::string& Name, unsigned int osiz = 0, unsigned int bsiz = 0)
30                 : DataProvider(mod, "hash/" + Name), out_size(osiz), block_size(bsiz)
31         {
32         }
33
34         virtual std::string GenerateRaw(const std::string& data) = 0;
35
36         virtual std::string ToPrintable(const std::string& raw)
37         {
38                 return BinToHex(raw);
39         }
40
41         virtual bool Compare(const std::string& input, const std::string& hash)
42         {
43                 return InspIRCd::TimingSafeCompare(Generate(input), hash);
44         }
45
46         std::string Generate(const std::string& data)
47         {
48                 return ToPrintable(GenerateRaw(data));
49         }
50
51         /** HMAC algorithm, RFC 2104 */
52         std::string hmac(const std::string& key, const std::string& msg)
53         {
54                 std::string hmac1, hmac2;
55                 std::string kbuf = key.length() > block_size ? GenerateRaw(key) : key;
56                 kbuf.resize(block_size);
57
58                 for (size_t n = 0; n < block_size; n++)
59                 {
60                         hmac1.push_back(static_cast<char>(kbuf[n] ^ 0x5C));
61                         hmac2.push_back(static_cast<char>(kbuf[n] ^ 0x36));
62                 }
63                 hmac2.append(msg);
64                 hmac1.append(GenerateRaw(hmac2));
65                 return GenerateRaw(hmac1);
66         }
67
68         bool IsKDF() const
69         {
70                 return (!block_size);
71         }
72 };