Botan 3.11.0
Crypto and TLS for C&
rng.cpp
Go to the documentation of this file.
1/*
2* (C) 2016 Jack Lloyd
3*
4* Botan is released under the Simplified BSD License (see license.txt)
5*/
6
7#include <botan/rng.h>
8
9#include <botan/exceptn.h>
10#include <botan/internal/loadstor.h>
11
12#if defined(BOTAN_HAS_ENTROPY_SOURCE)
13 #include <botan/entropy_src.h>
14#endif
15
16#if defined(BOTAN_HAS_SYSTEM_RNG)
17 #include <botan/system_rng.h>
18#endif
19
20#if defined(BOTAN_HAS_OS_UTILS)
21 #include <botan/internal/os_utils.h>
22#endif
23
24#include <array>
25
26namespace Botan {
27
28void RandomNumberGenerator::randomize_with_ts_input(std::span<uint8_t> output) {
29 if(this->accepts_input()) {
30 std::array<uint8_t, 32> additional_input = {0};
31
32#if defined(BOTAN_HAS_OS_UTILS)
33 store_le(std::span{additional_input}.subspan<0, 8>(), OS::get_high_resolution_clock());
34 store_le(std::span{additional_input}.subspan<8, 4>(), OS::get_process_id());
35 constexpr size_t offset = 12;
36#else
37 constexpr size_t offset = 0;
38#endif
39
40#if defined(BOTAN_HAS_SYSTEM_RNG)
41 system_rng().randomize(std::span{additional_input}.subspan<offset>());
42#else
43 BOTAN_UNUSED(offset);
44#endif
45
46 this->fill_bytes_with_input(output, additional_input);
47 } else {
48 this->fill_bytes_with_input(output, {});
49 }
50}
51
53 if(this->accepts_input()) {
54#if defined(BOTAN_HAS_ENTROPY_SOURCE)
55 return srcs.poll(*this, poll_bits);
56#else
57 BOTAN_UNUSED(srcs, poll_bits);
58#endif
59 }
60
61 return 0;
62}
63
65 if(this->accepts_input()) {
66 this->add_entropy(rng.random_vec(poll_bits / 8));
67 }
68}
69
70void Null_RNG::fill_bytes_with_input(std::span<uint8_t> output, std::span<const uint8_t> /* ignored */) {
71 // throw if caller tries to obtain random bytes
72 if(!output.empty()) {
73 throw PRNG_Unseeded("Null_RNG called");
74 }
75}
76
77} // namespace Botan
#define BOTAN_UNUSED
Definition assert.h:144
size_t poll(RandomNumberGenerator &rng, size_t bits, std::chrono::milliseconds timeout)
void randomize(std::span< uint8_t > output)
Definition rng.h:75
virtual bool accepts_input() const =0
void add_entropy(std::span< const uint8_t > input)
Definition rng.h:98
virtual size_t reseed_from_sources(Entropy_Sources &srcs, size_t poll_bits=RandomNumberGenerator::DefaultPollBits)
Definition rng.cpp:52
virtual void reseed_from_rng(RandomNumberGenerator &rng, size_t poll_bits=RandomNumberGenerator::DefaultPollBits)
Definition rng.cpp:64
void randomize_with_ts_input(std::span< uint8_t > output)
Definition rng.cpp:28
void random_vec(std::span< uint8_t > v)
Definition rng.h:204
virtual void fill_bytes_with_input(std::span< uint8_t > output, std::span< const uint8_t > input)=0
uint64_t BOTAN_TEST_API get_high_resolution_clock()
Definition os_utils.cpp:271
uint32_t BOTAN_TEST_API get_process_id()
Definition os_utils.cpp:76
RandomNumberGenerator & system_rng()
constexpr auto store_le(ParamTs &&... params)
Definition loadstor.h:736