xref: /openbmc/bmcweb/src/ossl_random.cpp (revision 41fe81c2)
1 #include "ossl_random.hpp"
2 
3 #include "logging.hpp"
4 
5 #include <cstddef>
6 #include <cstdint>
7 #include <string_view>
8 
9 extern "C"
10 {
11 #include <openssl/crypto.h>
12 #include <openssl/rand.h>
13 }
14 
15 #include <boost/uuid/random_generator.hpp>
16 #include <boost/uuid/uuid_io.hpp>
17 
18 #include <array>
19 #include <random>
20 #include <string>
21 
22 namespace bmcweb
23 {
operator ()()24 uint8_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 
getRandomUUID()37 std::string getRandomUUID()
38 {
39     using bmcweb::OpenSSLGenerator;
40     OpenSSLGenerator ossl;
41     return boost::uuids::to_string(
42         boost::uuids::basic_random_generator<OpenSSLGenerator>(ossl)());
43 }
44 
getRandomIdOfLength(size_t length)45 std::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 }
70 
constantTimeStringCompare(std::string_view a,std::string_view b)71 bool 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 
operator ()(std::string_view a,std::string_view b) const82 bool ConstantTimeCompare::operator()(std::string_view a,
83                                      std::string_view b) const
84 {
85     return constantTimeStringCompare(a, b);
86 }
87 
88 } // namespace bmcweb
89