Botan 3.14.1
Crypto and TLS for C&
hwrng.cpp
Go to the documentation of this file.
1/*
2* (C) 2016,2019,2020,2026 Jack Lloyd
3*
4* Botan is released under the Simplified BSD License (see license.txt)
5*/
6
7#include <botan/internal/hwrng.h>
8
9namespace Botan::HWRNG {
10
11bool available() {
12 return CPUID::has(feature());
13}
14
15std::optional<uint64_t> read() {
16 /*
17 * Intel DRNG Software Implementation Guide, Section 5.2.1
18 * It is recommended that applications attempt 10 retries in a tight loop
19 * in the unlikely event that the RDRAND instruction does not return a
20 * random number. This number is based on a binomial probability argument:
21 * given the design margins of the DRNG, the odds of ten failures in a row
22 * are astronomically small and would in fact be an indication of a larger
23 * CPU issue.
24 *
25 * PowerISA 3.0 p.78:
26 * When the error value is obtained, software is expected to repeat the
27 * operation. [...] The recommended number of attempts may be
28 * implementation specific. In the absence of other guidance, ten attempts
29 * should be adequate.
30 */
31 constexpr size_t HWRNG_RETRIES = 10;
32
33 for(size_t i = 0; i != HWRNG_RETRIES; ++i) {
34 if(const auto output = read_once()) {
35 return output;
36 }
37 }
38
39 return std::nullopt;
40}
41
42} // namespace Botan::HWRNG
static bool has(CPUID::Feature feat)
Definition cpuid.h:93
std::optional< uint64_t > read_once()
CPUID::Feature feature()
bool available()
Definition hwrng.cpp:11
std::optional< uint64_t > read()
Definition hwrng.cpp:15