xref: /openbmc/bmcweb/src/ossl_random.cpp (revision b7f3a82b)
12c6ffdb0SEd Tanous #include "ossl_random.hpp"
22c6ffdb0SEd Tanous 
3*b7f3a82bSEd Tanous extern "C"
4*b7f3a82bSEd Tanous {
5*b7f3a82bSEd Tanous #include <openssl/rand.h>
6*b7f3a82bSEd Tanous }
7*b7f3a82bSEd Tanous 
8f0b59af4SEd Tanous #include <boost/uuid/random_generator.hpp>
92c6ffdb0SEd Tanous #include <boost/uuid/uuid_io.hpp>
102c6ffdb0SEd Tanous 
11*b7f3a82bSEd Tanous #include <array>
12*b7f3a82bSEd Tanous #include <random>
13f0b59af4SEd Tanous #include <string>
14f0b59af4SEd Tanous 
15*b7f3a82bSEd Tanous namespace bmcweb
16*b7f3a82bSEd Tanous {
operator ()()17*b7f3a82bSEd Tanous uint8_t OpenSSLGenerator::operator()()
18*b7f3a82bSEd Tanous {
19*b7f3a82bSEd Tanous     uint8_t index = 0;
20*b7f3a82bSEd Tanous     int rc = RAND_bytes(&index, sizeof(index));
21*b7f3a82bSEd Tanous     if (rc != opensslSuccess)
22*b7f3a82bSEd Tanous     {
23*b7f3a82bSEd Tanous         BMCWEB_LOG_ERROR("Cannot get random number");
24*b7f3a82bSEd Tanous         err = true;
25*b7f3a82bSEd Tanous     }
26*b7f3a82bSEd Tanous 
27*b7f3a82bSEd Tanous     return index;
28*b7f3a82bSEd Tanous }
29*b7f3a82bSEd Tanous 
getRandomUUID()30*b7f3a82bSEd Tanous std::string getRandomUUID()
312c6ffdb0SEd Tanous {
322c6ffdb0SEd Tanous     using bmcweb::OpenSSLGenerator;
332c6ffdb0SEd Tanous     OpenSSLGenerator ossl;
342c6ffdb0SEd Tanous     return boost::uuids::to_string(
352c6ffdb0SEd Tanous         boost::uuids::basic_random_generator<OpenSSLGenerator>(ossl)());
362c6ffdb0SEd Tanous }
37*b7f3a82bSEd Tanous 
getRandomIdOfLength(size_t length)38*b7f3a82bSEd Tanous std::string getRandomIdOfLength(size_t length)
39*b7f3a82bSEd Tanous {
40*b7f3a82bSEd Tanous     static constexpr std::array<char, 62> alphanum = {
41*b7f3a82bSEd Tanous         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C',
42*b7f3a82bSEd Tanous         'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
43*b7f3a82bSEd Tanous         'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c',
44*b7f3a82bSEd Tanous         'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
45*b7f3a82bSEd Tanous         'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
46*b7f3a82bSEd Tanous 
47*b7f3a82bSEd Tanous     std::string token;
48*b7f3a82bSEd Tanous     token.resize(length, '0');
49*b7f3a82bSEd Tanous     std::uniform_int_distribution<size_t> dist(0, alphanum.size() - 1);
50*b7f3a82bSEd Tanous 
51*b7f3a82bSEd Tanous     bmcweb::OpenSSLGenerator gen;
52*b7f3a82bSEd Tanous 
53*b7f3a82bSEd Tanous     for (char& tokenChar : token)
54*b7f3a82bSEd Tanous     {
55*b7f3a82bSEd Tanous         tokenChar = alphanum[dist(gen)];
56*b7f3a82bSEd Tanous         if (gen.error())
57*b7f3a82bSEd Tanous         {
58*b7f3a82bSEd Tanous             return "";
59*b7f3a82bSEd Tanous         }
60*b7f3a82bSEd Tanous     }
61*b7f3a82bSEd Tanous     return token;
62*b7f3a82bSEd Tanous }
63*b7f3a82bSEd Tanous } // namespace bmcweb
64