2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2010 Daniel De Graaf <danieldg@inspircd.org>
5 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
6 * Copyright (C) 2005-2007 Craig Edwards <craigedwards@brainbox.cc>
8 * This file is part of InspIRCd. InspIRCd is free software: you can
9 * redistribute it and/or modify it under the terms of the GNU General Public
10 * License as published by the Free Software Foundation, version 2.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 static const char hextable[] = "0123456789abcdef";
26 std::string BinToHex(const void* raw, size_t l)
28 const char* data = static_cast<const char*>(raw);
31 for (size_t i = 0; i < l; i++)
33 unsigned char c = data[i];
34 rv.push_back(hextable[c >> 4]);
35 rv.push_back(hextable[c & 0xF]);
40 static const char b64table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
42 std::string BinToBase64(const std::string& data_str, const char* table, char pad)
48 uint8_t* data = (uint8_t*)data_str.data();
51 while (i + 2 < data_str.length())
53 buffer = (data[i] << 16 | data[i+1] << 8 | data[i+2]);
54 rv.push_back(table[0x3F & (buffer >> 18)]);
55 rv.push_back(table[0x3F & (buffer >> 12)]);
56 rv.push_back(table[0x3F & (buffer >> 6)]);
57 rv.push_back(table[0x3F & (buffer >> 0)]);
60 if (data_str.length() == i)
62 // no extra characters
64 else if (data_str.length() == i + 1)
66 buffer = data[i] << 16;
67 rv.push_back(table[0x3F & (buffer >> 18)]);
68 rv.push_back(table[0x3F & (buffer >> 12)]);
75 else if (data_str.length() == i + 2)
77 buffer = (data[i] << 16 | data[i+1] << 8);
78 rv.push_back(table[0x3F & (buffer >> 18)]);
79 rv.push_back(table[0x3F & (buffer >> 12)]);
80 rv.push_back(table[0x3F & (buffer >> 6)]);
87 std::string Base64ToBin(const std::string& data_str, const char* table)
94 const char* data = data_str.c_str();
98 const char* find = strchr(table, *data++);
99 if (!find || find >= table + 64)
101 buffer = (buffer << 6) | (find - table);
106 rv.push_back((buffer >> bitcount) & 0xFF);
112 bool InspIRCd::TimingSafeCompare(const std::string& one, const std::string& two)
114 if (one.length() != two.length())
117 unsigned int diff = 0;
118 for (std::string::const_iterator i = one.begin(), j = two.begin(); i != one.end(); ++i, ++j)
120 unsigned char a = static_cast<unsigned char>(*i);
121 unsigned char b = static_cast<unsigned char>(*j);