blob: 419fe31455eb4e49c6fdfb029353cb2e1933d461 [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{
5#include <openssl/rand.h>
6}
7
Ed Tanousf0b59af2024-03-20 13:38:04 -07008#include <boost/uuid/random_generator.hpp>
Ed Tanous2c6ffdb2023-06-28 11:28:38 -07009#include <boost/uuid/uuid_io.hpp>
10
Ed Tanousb7f3a822024-06-05 08:45:25 -070011#include <array>
12#include <random>
Ed Tanousf0b59af2024-03-20 13:38:04 -070013#include <string>
14
Ed Tanousb7f3a822024-06-05 08:45:25 -070015namespace bmcweb
16{
17uint8_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
30std::string getRandomUUID()
Ed Tanous2c6ffdb2023-06-28 11:28:38 -070031{
32 using bmcweb::OpenSSLGenerator;
33 OpenSSLGenerator ossl;
34 return boost::uuids::to_string(
35 boost::uuids::basic_random_generator<OpenSSLGenerator>(ossl)());
36}
Ed Tanousb7f3a822024-06-05 08:45:25 -070037
38std::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