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