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