1 #include "ossl_random.hpp" 2 3 extern "C" 4 { 5 #include <openssl/crypto.h> 6 #include <openssl/rand.h> 7 } 8 9 #include <boost/uuid/random_generator.hpp> 10 #include <boost/uuid/uuid_io.hpp> 11 12 #include <array> 13 #include <random> 14 #include <string> 15 16 namespace bmcweb 17 { 18 uint8_t OpenSSLGenerator::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 std::string getRandomUUID() 32 { 33 using bmcweb::OpenSSLGenerator; 34 OpenSSLGenerator ossl; 35 return boost::uuids::to_string( 36 boost::uuids::basic_random_generator<OpenSSLGenerator>(ossl)()); 37 } 38 39 std::string getRandomIdOfLength(size_t length) 40 { 41 static constexpr std::array<char, 62> alphanum = { 42 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 43 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 44 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 45 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 46 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; 47 48 std::string token; 49 token.resize(length, '0'); 50 std::uniform_int_distribution<size_t> dist(0, alphanum.size() - 1); 51 52 bmcweb::OpenSSLGenerator gen; 53 54 for (char& tokenChar : token) 55 { 56 tokenChar = alphanum[dist(gen)]; 57 if (gen.error()) 58 { 59 return ""; 60 } 61 } 62 return token; 63 } 64 65 bool constantTimeStringCompare(std::string_view a, std::string_view b) 66 { 67 // Important note, this function is ONLY constant time if the two input 68 // sizes are the same 69 if (a.size() != b.size()) 70 { 71 return false; 72 } 73 return CRYPTO_memcmp(a.data(), b.data(), a.size()) == 0; 74 } 75 76 bool ConstantTimeCompare::operator()(std::string_view a, 77 std::string_view b) const 78 { 79 return constantTimeStringCompare(a, b); 80 } 81 82 } // namespace bmcweb 83