blob: eff473863867929a8dfc8c5009e1fc083f5e5642 [file] [log] [blame]
Ed Tanous2c6ffdb2023-06-28 11:28:38 -07001#include "ossl_random.hpp"
2
Ed Tanous41fe81c2024-09-02 15:08:41 -07003#include "logging.hpp"
4
5#include <cstddef>
6#include <cstdint>
7#include <string_view>
8
Ed Tanousb7f3a822024-06-05 08:45:25 -07009extern "C"
10{
Ed Tanous724985f2024-06-05 09:19:06 -070011#include <openssl/crypto.h>
Ed Tanousb7f3a822024-06-05 08:45:25 -070012#include <openssl/rand.h>
13}
14
Ed Tanousf0b59af2024-03-20 13:38:04 -070015#include <boost/uuid/random_generator.hpp>
Ed Tanous2c6ffdb2023-06-28 11:28:38 -070016#include <boost/uuid/uuid_io.hpp>
17
Ed Tanousb7f3a822024-06-05 08:45:25 -070018#include <array>
19#include <random>
Ed Tanousf0b59af2024-03-20 13:38:04 -070020#include <string>
21
Ed Tanousb7f3a822024-06-05 08:45:25 -070022namespace bmcweb
23{
24uint8_t OpenSSLGenerator::operator()()
25{
26 uint8_t index = 0;
27 int rc = RAND_bytes(&index, sizeof(index));
28 if (rc != opensslSuccess)
29 {
30 BMCWEB_LOG_ERROR("Cannot get random number");
31 err = true;
32 }
33
34 return index;
35}
36
37std::string getRandomUUID()
Ed Tanous2c6ffdb2023-06-28 11:28:38 -070038{
39 using bmcweb::OpenSSLGenerator;
40 OpenSSLGenerator ossl;
41 return boost::uuids::to_string(
42 boost::uuids::basic_random_generator<OpenSSLGenerator>(ossl)());
43}
Ed Tanousb7f3a822024-06-05 08:45:25 -070044
45std::string getRandomIdOfLength(size_t length)
46{
47 static constexpr std::array<char, 62> alphanum = {
48 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C',
49 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
50 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c',
51 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
52 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
53
54 std::string token;
55 token.resize(length, '0');
56 std::uniform_int_distribution<size_t> dist(0, alphanum.size() - 1);
57
58 bmcweb::OpenSSLGenerator gen;
59
60 for (char& tokenChar : token)
61 {
62 tokenChar = alphanum[dist(gen)];
63 if (gen.error())
64 {
65 return "";
66 }
67 }
68 return token;
69}
Ed Tanous724985f2024-06-05 09:19:06 -070070
71bool constantTimeStringCompare(std::string_view a, std::string_view b)
72{
73 // Important note, this function is ONLY constant time if the two input
74 // sizes are the same
75 if (a.size() != b.size())
76 {
77 return false;
78 }
79 return CRYPTO_memcmp(a.data(), b.data(), a.size()) == 0;
80}
81
82bool ConstantTimeCompare::operator()(std::string_view a,
83 std::string_view b) const
84{
85 return constantTimeStringCompare(a, b);
86}
87
Ed Tanousb7f3a822024-06-05 08:45:25 -070088} // namespace bmcweb