]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/hash.h
Fixes for bug #12
[user/henk/code/inspircd.git] / src / modules / hash.h
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2010 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #ifndef HASH_H
15 #define HASH_H
16
17 #include "modules.h"
18
19 class HashProvider : public DataProvider
20 {
21  public:
22         const unsigned int out_size;
23         const unsigned int block_size;
24         HashProvider(Module* mod, const std::string& Name, int osiz, int bsiz)
25                 : DataProvider(mod, Name), out_size(osiz), block_size(bsiz) {}
26         virtual std::string sum(const std::string& data) = 0;
27         inline std::string hexsum(const std::string& data)
28         {
29                 return BinToHex(sum(data));
30         }
31
32         inline std::string b64sum(const std::string& data)
33         {
34                 return BinToBase64(sum(data), NULL, 0);
35         }
36
37         /** Allows the IVs for the hash to be specified. As the choice of initial IV is
38          * important for the security of a hash, this should not be used except to
39          * maintain backwards compatability. This also allows you to change the hex
40          * sequence from its default of "0123456789abcdef", which does not improve the
41          * strength of the output, but helps confuse those attempting to implement it.
42          *
43          * Example:
44          * \code
45          * unsigned int iv[] = { 0xFFFFFFFF, 0x00000000, 0xAAAAAAAA, 0xCCCCCCCC };
46          * std::string result = Hash.sumIV(iv, "fedcba9876543210", "data");
47          * \endcode
48          */
49         virtual std::string sumIV(unsigned int* IV, const char* HexMap, const std::string &sdata) = 0;
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 ? sum(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(sum(hmac2));
65                 return sum(hmac1);
66         }
67 };
68
69 #endif
70