|
7 | 7 | #include "sha1.h" |
8 | 8 | #include "sha256.h" |
9 | 9 | #include "key_vault.h" |
| 10 | +#include <charconv> |
| 11 | +#include <cstdlib> |
10 | 12 | #include <cstring> |
11 | | -#include <stdio.h> |
12 | | -#include <time.h> |
| 13 | +#include <cstdio> |
| 14 | +#include <ctime> |
13 | 15 | #include "Utilities/StrUtil.h" |
14 | 16 | #include "Utilities/File.h" |
15 | 17 |
|
|
21 | 23 | // Auxiliary functions (endian swap, xor). |
22 | 24 |
|
23 | 25 | // Hex string conversion auxiliary functions. |
24 | | -u64 hex_to_u64(const char* hex_str) |
| 26 | +void hex_to_bytes(unsigned char* data, std::string_view hex_str, unsigned int str_length) |
25 | 27 | { |
26 | | - auto length = std::strlen(hex_str); |
27 | | - u64 tmp = 0; |
28 | | - u64 result = 0; |
29 | | - char c; |
30 | | - |
31 | | - while (length--) |
32 | | - { |
33 | | - c = *hex_str++; |
34 | | - if((c >= '0') && (c <= '9')) |
35 | | - tmp = c - '0'; |
36 | | - else if((c >= 'a') && (c <= 'f')) |
37 | | - tmp = c - 'a' + 10; |
38 | | - else if((c >= 'A') && (c <= 'F')) |
39 | | - tmp = c - 'A' + 10; |
40 | | - else |
41 | | - tmp = 0; |
42 | | - result |= (tmp << (length * 4)); |
43 | | - } |
44 | | - |
45 | | - return result; |
46 | | -} |
47 | | - |
48 | | -void hex_to_bytes(unsigned char* data, const char* hex_str, unsigned int str_length) |
49 | | -{ |
50 | | - const auto strn_length = (str_length > 0) ? str_length : std::strlen(hex_str); |
51 | | - auto data_length = strn_length / 2; |
52 | | - char tmp_buf[3] = {0, 0, 0}; |
| 28 | + const auto strn_length = (str_length > 0) ? str_length : hex_str.size(); |
53 | 29 |
|
54 | 30 | // Don't convert if the string length is odd. |
55 | 31 | if ((strn_length % 2) == 0) |
56 | 32 | { |
57 | | - while (data_length--) |
| 33 | + for (size_t i = 0; i < strn_length; i += 2) |
58 | 34 | { |
59 | | - tmp_buf[0] = *hex_str++; |
60 | | - tmp_buf[1] = *hex_str++; |
61 | | - |
62 | | - *data++ = static_cast<u8>(hex_to_u64(tmp_buf) & 0xFF); |
| 35 | + const auto [ptr, err] = std::from_chars(hex_str.data() + i, hex_str.data() + i + 2, *data++, 16); |
| 36 | + if (err != std::errc()) |
| 37 | + { |
| 38 | + fmt::throw_exception("Failed to read hex string: %s", std::make_error_code(err).message()); |
| 39 | + } |
63 | 40 | } |
64 | 41 | } |
65 | 42 | } |
66 | 43 |
|
67 | | - |
68 | 44 | // Crypto functions (AES128-CBC, AES128-ECB, SHA1-HMAC and AES-CMAC). |
69 | 45 | void aescbc128_decrypt(unsigned char *key, unsigned char *iv, unsigned char *in, unsigned char *out, usz len) |
70 | 46 | { |
|
0 commit comments