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