SHA256
55 lines
1.6 KiB
C++
55 lines
1.6 KiB
C++
#pragma once
|
|
|
|
#include <cstddef>
|
|
#include <cstdint>
|
|
#include <cstring>
|
|
#include <string>
|
|
#include <vector>
|
|
|
|
namespace regkey {
|
|
static constexpr char ALPHABET[] = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
|
|
inline std::string encode(const uint8_t *data, size_t length) {
|
|
size_t zeros = 0;
|
|
while (zeros < length && data[zeros] == 0) ++zeros;
|
|
std::vector<uint8_t> digits;
|
|
for (size_t i = zeros; i < length; ++i) {
|
|
unsigned carry = data[i];
|
|
for (auto &digit : digits) {
|
|
carry += 256U * digit;
|
|
digit = carry % 58U;
|
|
carry /= 58U;
|
|
}
|
|
while (carry) { digits.push_back(carry % 58U); carry /= 58U; }
|
|
}
|
|
std::string result(zeros, '1');
|
|
for (auto it = digits.rbegin(); it != digits.rend(); ++it) result += ALPHABET[*it];
|
|
return result;
|
|
}
|
|
|
|
inline bool decode32(const char *text, uint8_t out[32]) {
|
|
if (!text || !*text) return false;
|
|
const size_t length = strlen(text);
|
|
if (length > 45) return false;
|
|
size_t zeros = 0;
|
|
while (zeros < length && text[zeros] == '1') ++zeros;
|
|
std::vector<uint8_t> bytes;
|
|
for (size_t i = zeros; i < length; ++i) {
|
|
const char *found = strchr(ALPHABET, text[i]);
|
|
if (!found) return false;
|
|
unsigned carry = found - ALPHABET;
|
|
for (auto &byte : bytes) {
|
|
carry += 58U * byte;
|
|
byte = carry & 255U;
|
|
carry >>= 8U;
|
|
}
|
|
while (carry) { bytes.push_back(carry & 255U); carry >>= 8U; }
|
|
if (zeros + bytes.size() > 32) return false;
|
|
}
|
|
if (zeros + bytes.size() != 32) return false;
|
|
memset(out, 0, 32);
|
|
for (size_t i = 0; i < bytes.size(); ++i) out[31 - i] = bytes[i];
|
|
return encode(out, 32) == text;
|
|
}
|
|
} // namespace regkey
|