Orbit Framework 2.0.0
A high-performance asynchronous C++20 HTTP server framework.
Loading...
Searching...
No Matches
Random.hpp
Go to the documentation of this file.
1#pragma once
3#include <openssl/crypto.h>
4#include <openssl/rand.h>
5#include <stdexcept>
6#include <string>
7#include <string_view>
8#include <vector>
9
10namespace orbit::utils {
11
21inline std::string secure_random_hex(size_t num_bytes) {
22 std::vector<unsigned char> bytes(num_bytes);
23 if (RAND_bytes(bytes.data(), static_cast<int>(bytes.size())) != 1) {
24 throw std::runtime_error("RAND_bytes failed");
25 }
26 static const char hex[] = "0123456789abcdef";
27 std::string out;
28 out.reserve(num_bytes * 2);
29 for (unsigned char b : bytes) {
30 out.push_back(hex[b >> 4]);
31 out.push_back(hex[b & 0x0F]);
32 }
33 return out;
34}
35
39inline bool constant_time_equals(std::string_view a, std::string_view b) {
40 if (a.size() != b.size()) return false;
41 return CRYPTO_memcmp(a.data(), b.data(), a.size()) == 0;
42}
43
44} // namespace utils
Definition legacy_namespaces.hpp:26
std::string secure_random_hex(size_t num_bytes)
Returns num_bytes of cryptographically secure randomness, hex-encoded.
Definition Random.hpp:21
bool constant_time_equals(std::string_view a, std::string_view b)
Compares two secrets in time independent of where they differ.
Definition Random.hpp:39