blob: e22ed7f71755296ed71d9ba0703e2c60b61f05de [file] [log] [blame]
Ed Tanous40e9b922024-09-10 13:50:16 -07001// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright OpenBMC Authors
Ed Tanous2c6ffdb2023-06-28 11:28:38 -07003#include "ossl_random.hpp"
4
Ed Tanous41fe81c2024-09-02 15:08:41 -07005#include "logging.hpp"
6
7#include <cstddef>
8#include <cstdint>
9#include <string_view>
10
Ed Tanousb7f3a822024-06-05 08:45:25 -070011extern "C"
12{
Ed Tanous724985f2024-06-05 09:19:06 -070013#include <openssl/crypto.h>
Ed Tanousb7f3a822024-06-05 08:45:25 -070014#include <openssl/rand.h>
15}
16
Ed Tanous04208852024-12-16 09:34:27 -080017#include <boost/uuid/basic_random_generator.hpp>
Ed Tanous2c6ffdb2023-06-28 11:28:38 -070018#include <boost/uuid/uuid_io.hpp>
19
Ed Tanousb7f3a822024-06-05 08:45:25 -070020#include <array>
21#include <random>
Ed Tanousf0b59af2024-03-20 13:38:04 -070022#include <string>
23
Ed Tanousb7f3a822024-06-05 08:45:25 -070024namespace bmcweb
25{
26uint8_t OpenSSLGenerator::operator()()
27{
28 uint8_t index = 0;
29 int rc = RAND_bytes(&index, sizeof(index));
30 if (rc != opensslSuccess)
31 {
32 BMCWEB_LOG_ERROR("Cannot get random number");
33 err = true;
34 }
35
36 return index;
37}
38
39std::string getRandomUUID()
Ed Tanous2c6ffdb2023-06-28 11:28:38 -070040{
41 using bmcweb::OpenSSLGenerator;
42 OpenSSLGenerator ossl;
43 return boost::uuids::to_string(
44 boost::uuids::basic_random_generator<OpenSSLGenerator>(ossl)());
45}
Ed Tanousb7f3a822024-06-05 08:45:25 -070046
47std::string getRandomIdOfLength(size_t length)
48{
49 static constexpr std::array<char, 62> alphanum = {
50 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C',
51 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
52 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c',
53 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
54 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
55
56 std::string token;
57 token.resize(length, '0');
58 std::uniform_int_distribution<size_t> dist(0, alphanum.size() - 1);
59
60 bmcweb::OpenSSLGenerator gen;
61
62 for (char& tokenChar : token)
63 {
64 tokenChar = alphanum[dist(gen)];
65 if (gen.error())
66 {
67 return "";
68 }
69 }
70 return token;
71}
Ed Tanous724985f2024-06-05 09:19:06 -070072
73bool constantTimeStringCompare(std::string_view a, std::string_view b)
74{
75 // Important note, this function is ONLY constant time if the two input
76 // sizes are the same
77 if (a.size() != b.size())
78 {
79 return false;
80 }
81 return CRYPTO_memcmp(a.data(), b.data(), a.size()) == 0;
82}
83
84bool ConstantTimeCompare::operator()(std::string_view a,
85 std::string_view b) const
86{
87 return constantTimeStringCompare(a, b);
88}
89
Ed Tanousb7f3a822024-06-05 08:45:25 -070090} // namespace bmcweb