xref: /openbmc/bmcweb/include/ossl_random.hpp (revision 62598e31)
1 #pragma once
2 
3 #include <openssl/rand.h>
4 
5 #include <iostream>
6 #include <limits>
7 #include <string>
8 
9 namespace bmcweb
10 {
11 
12 struct OpenSSLGenerator
13 {
14     uint8_t operator()()
15     {
16         uint8_t index = 0;
17         int rc = RAND_bytes(&index, sizeof(index));
18         if (rc != opensslSuccess)
19         {
20             std::cerr << "Cannot get random number\n";
21             err = true;
22         }
23 
24         return index;
25     }
26 
27     static constexpr uint8_t max()
28     {
29         return std::numeric_limits<uint8_t>::max();
30     }
31     static constexpr uint8_t min()
32     {
33         return std::numeric_limits<uint8_t>::min();
34     }
35 
36     bool error() const
37     {
38         return err;
39     }
40 
41     // all generators require this variable
42     using result_type = uint8_t;
43 
44   private:
45     // RAND_bytes() returns 1 on success, 0 otherwise. -1 if bad function
46     static constexpr int opensslSuccess = 1;
47     bool err = false;
48 };
49 
50 std::string getRandomUUID();
51 
52 } // namespace bmcweb
53