#include #include #include #include namespace ts6bot::crypto { static void rand_bytes(std::span out) { if (out.empty()) { return; } if (RAND_bytes(out.data(), static_cast(out.size())) != 1) { throw std::runtime_error("RAND_bytes failed"); } } std::string GenerateCodeVerifier(std::size_t length) { if (length < 43 || length > 128) { throw std::runtime_error("code_verifier length must be 43..128"); } static constexpr char kAlphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789" "-._~"; std::vector rnd(length); rand_bytes(rnd); std::string out; out.reserve(length); for (std::uint8_t b : rnd) { out.push_back(kAlphabet[b % (sizeof(kAlphabet) - 1)]); } return out; } std::string Base64UrlEncode(std::span data) { static constexpr char tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; std::string out; out.reserve(((data.size() + 2) / 3) * 4); std::size_t i = 0; while (i + 3 <= data.size()) { std::uint32_t n = (static_cast(data[i]) << 16) | (static_cast(data[i + 1]) << 8) | (static_cast(data[i + 2])); out.push_back(tbl[(n >> 18) & 63]); out.push_back(tbl[(n >> 12) & 63]); out.push_back(tbl[(n >> 6) & 63]); out.push_back(tbl[n & 63]); i += 3; } std::size_t rem = data.size() - i; if (rem == 1) { std::uint32_t n = (static_cast(data[i]) << 16); out.push_back(tbl[(n >> 18) & 63]); out.push_back(tbl[(n >> 12) & 63]); out.push_back('='); out.push_back('='); } else if (rem == 2) { std::uint32_t n = (static_cast(data[i]) << 16) | (static_cast(data[i + 1]) << 8); out.push_back(tbl[(n >> 18) & 63]); out.push_back(tbl[(n >> 12) & 63]); out.push_back(tbl[(n >> 6) & 63]); out.push_back('='); } // base64url + no padding for (char& c : out) { if (c == '+') { c = '-'; } else if (c == '/') { c = '_'; } } while (!out.empty() && out.back() == '=') { out.pop_back(); } return out; } std::string GenerateState(std::size_t bytes) { std::vector rnd(bytes); rand_bytes(rnd); return Base64UrlEncode(rnd); } std::vector Sha256(std::span data) { std::vector out(SHA256_DIGEST_LENGTH); SHA256_CTX ctx; if (SHA256_Init(&ctx) != 1) { throw std::runtime_error("SHA256_Init failed"); } if (!data.empty() && SHA256_Update(&ctx, data.data(), data.size()) != 1) { throw std::runtime_error("SHA256_Update failed"); } if (SHA256_Final(out.data(), &ctx) != 1) { throw std::runtime_error("SHA256_Final failed"); } return out; } std::vector Sha256(std::span data) { auto* ptr = reinterpret_cast(data.data()); return Sha256(std::span{ptr, data.size()}); } } // namespace ts6bot::crypto