2#include "pedigree/kernel/LockGuard.h"
3#include "pedigree/kernel/Spinlock.h"
4#include "pedigree/kernel/utilities/SecureRandom.h"
5#include "pedigree/kernel/utilities/lib.h"
9uint8_t randomKey[32] = {};
10bool randomReady =
false;
12bool initialiseLocked() {
15 uint8_t seed[32] = {};
16 if (hardware_random_bytes(seed,
sizeof(seed)) ==
sizeof(seed)) {
17 for (
size_t i = 0; i <
sizeof(seed); ++i)
18 randomKey[i] = seed[i];
21 pedigree_random::erase(seed,
sizeof(seed));
26extern "C" int secure_random_seed(
const void* buffer,
size_t length) {
27 if (!buffer || length !=
sizeof(randomKey))
30 const auto* seed =
static_cast<const uint8_t*
>(buffer);
32 if (initialiseLocked()) {
34 pedigree_random::hmac_sha256(randomKey, seed, length, next);
36 for (
size_t i = 0; i <
sizeof(next); ++i)
39 for (
size_t i = 0; i <
sizeof(next); ++i)
40 randomKey[i] = next[i];
42 pedigree_random::erase(next,
sizeof(next));
46extern "C" size_t secure_random_bytes(
void* buffer,
size_t length) {
47 if (!buffer || !length)
49 auto* output =
static_cast<uint8_t*
>(buffer);
51 while (produced < length) {
54 if (!initialiseLocked())
56 const uint8_t nonce[12] = {};
58 pedigree_random::chacha20_block(randomKey, nonce, 0, block);
59 for (
size_t i = 0; i <
sizeof(randomKey); ++i)
60 randomKey[i] = block[i];
61 const size_t count = length - produced < 32 ? length - produced : 32;
62 for (
size_t i = 0; i < count; ++i)
63 output[produced + i] = block[32 + i];
66 pedigree_random::erase(block,
sizeof(block));