1 // Copyright 2020 The Pigweed Authors
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
7 // https://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
20 #include "pw_bytes/span.h"
21 #include "pw_status/status_with_size.h"
23 namespace pw::random {
25 // A random generator uses injected entropy to generate random values. Many of
26 // the guarantees for this interface are provided at the level of the
27 // implementations. In general:
28 // * DO NOT assume a generator is cryptographically secure.
29 // * DO NOT assume uniformity of generated data.
30 // * DO assume a generator can be exhausted.
31 class RandomGenerator {
33 virtual ~RandomGenerator() = default;
36 StatusWithSize GetInt(T& dest) {
37 static_assert(std::is_integral<T>::value,
38 "Use Get() for non-integral types");
39 return Get({reinterpret_cast<std::byte*>(&dest), sizeof(T)});
42 // Populates the destination buffer with a randomly generated value. Returns:
43 // OK - Successfully filled the destination buffer with random data.
44 // RESOURCE_EXHAUSTED - Filled the buffer with the returned number of bytes.
45 // The returned size is number of complete bytes with random data.
46 virtual StatusWithSize Get(ByteSpan dest) = 0;
48 // Injects entropy into the pool. `data` may have up to 32 bits of random
49 // entropy. If the number of bits of entropy is less than 32, entropy is
50 // assumed to be stored in the least significant bits of `data`.
51 virtual void InjectEntropyBits(uint32_t data, uint_fast8_t num_bits) = 0;
53 // Injects entropy into the pool byte-by-byte.
54 void InjectEntropy(ConstByteSpan data) {
55 for (std::byte b : data) {
56 InjectEntropyBits(std::to_integer<uint32_t>(b), /*num_bits=*/8);
61 } // namespace pw::random