1 | /* |
---|
2 | * Chrome Token Signing Native Host |
---|
3 | * |
---|
4 | * This library is free software; you can redistribute it and/or |
---|
5 | * modify it under the terms of the GNU Lesser General Public |
---|
6 | * License as published by the Free Software Foundation; either |
---|
7 | * version 2.1 of the License, or (at your option) any later version. |
---|
8 | * |
---|
9 | * This library is distributed in the hope that it will be useful, |
---|
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
---|
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
---|
12 | * Lesser General Public License for more details. |
---|
13 | * |
---|
14 | * You should have received a copy of the GNU Lesser General Public |
---|
15 | * License along with this library; if not, write to the Free Software |
---|
16 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA |
---|
17 | */ |
---|
18 | |
---|
19 | #include "binaryutils.h" |
---|
20 | #include <stdio.h> |
---|
21 | #include <stdexcept> |
---|
22 | |
---|
23 | using namespace std; |
---|
24 | |
---|
25 | vector<unsigned char> BinaryUtils::hex2bin(const string &hex) { |
---|
26 | if (hex.size() % 2 == 1) |
---|
27 | throw runtime_error("Hex is incorrect"); |
---|
28 | |
---|
29 | vector<unsigned char> bin(hex.size() / 2, 0); |
---|
30 | unsigned char *c = &bin[0]; |
---|
31 | const char *h = hex.c_str(); |
---|
32 | while (*h) { |
---|
33 | int x; |
---|
34 | sscanf(h, "%2X", &x); |
---|
35 | *c = x; |
---|
36 | c++; |
---|
37 | h += 2; |
---|
38 | } |
---|
39 | return bin; |
---|
40 | } |
---|
41 | |
---|
42 | string BinaryUtils::bin2hex(const vector<unsigned char> &bin) { |
---|
43 | string hex(bin.size() * 2, 0); |
---|
44 | for (size_t j = 0; j < bin.size(); ++j) |
---|
45 | sprintf(&hex[j * 2], "%02X", (unsigned char) bin.at(j)); |
---|
46 | return hex; |
---|
47 | } |
---|