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