CHERIoT RTOS
A compartmentalised RTOS for CHERIoT hardware
Loading...
Searching...
No Matches
randombytes.h
Go to the documentation of this file.
1#pragma once
2
3#include <cdefs.h>
4#include <stddef.h>
5#include <stdint.h>
6
7#ifdef __cplusplus
8# include <concepts>
9#endif
10
11/**
12 * \file
13 *
14 * API for accessing a shared entropy source in the `randombytes` compartment.
15 */
16
17__BEGIN_DECLS
18
19/**
20 * Populate `output` with `n` bytes of entropy from the system's entropy source.
21 *
22 * This will be cryptographically secure entropy if and only if the system
23 * entropy source is cryptographically secure.
24 *
25 * Returns 0 on success.
26 */
27__cheriot_compartment("randombytes") int randombytes(uint8_t *output, size_t n);
28
29__END_DECLS
30
31#ifdef __cplusplus
32
33/**
34 * Populate a container-like `output` with entropy using its `.size()` and
35 * `.data`() APIs.
36 *
37 * This will be cryptographically secure entropy if and only if the system
38 * entropy source is cryptographically secure.
39 *
40 * Returns 0 on success.
41 */
42template<typename T>
43 requires requires(T &v) {
44 requires std::is_pointer_v<decltype(v.data())>;
45 requires std::is_convertible_v<decltype(v.size()), size_t>;
46 }
47__always_inline int randombytes(T &output)
48{
49 return randombytes(reinterpret_cast<uint8_t *>(output.data()),
50 output.size() * sizeof(*output.data()));
51}
52
53/**
54 * Populate an `output` array of length `N` with `N * sizeof(output[0])` bytes
55 * of entropy from the system's entropy source.
56 *
57 * This will be cryptographically secure entropy if and only if the system
58 * entropy source is cryptographically secure.
59 *
60 * Returns 0 on success.
61 */
62template<typename T, size_t N>
63 requires std::is_arithmetic_v<T>
64__always_inline int randombytes(T (&output)[N])
65{
66 return randombytes(reinterpret_cast<uint8_t *>(&output), sizeof(output));
67}
68
69/**
70 * Populate `output` with `sizeof(output)` bytes of entropy from the system's
71 * entropy source.
72 *
73 * This will be cryptographically secure entropy if and only if the system
74 * entropy source is cryptographically secure.
75 *
76 * Returns 0 on success.
77 */
78template<typename T>
79 requires std::is_arithmetic_v<T>
80__always_inline int randombytes(T &output)
81{
82 return randombytes(reinterpret_cast<uint8_t *>(&output), sizeof(output));
83}
84
85#endif
__cheriot_compartment("randombytes") int randombytes(uint8_t *output
Populate output with n bytes of entropy from the system's entropy source.
int randombytes(T &output)
Populate a container-like output with entropy using its .size() and .data() APIs.
Definition randombytes.h:47