1/* Copyright (c) (2010-2020,2022) Apple Inc. All rights reserved.
2 *
3 * corecrypto is licensed under Apple Inc.’s Internal Use License Agreement (which
4 * is contained in the License.txt file distributed with corecrypto) and only to
5 * people who accept that license. IMPORTANT: Any license rights granted to you by
6 * Apple Inc. (if any) are limited to internal use within your organization only on
7 * devices and computers you own or control, for the sole purpose of verifying the
8 * security characteristics and correct functioning of the Apple Software. You may
9 * not, directly or indirectly, redistribute the Apple Software or any portions thereof.
10 */
11
12#ifndef _CORECRYPTO_CCRNG_H_
13#define _CORECRYPTO_CCRNG_H_
14
15#include <corecrypto/cc.h>
16
17#define CCRNG_STATE_COMMON \
18 int (*CC_SPTR(ccrng_state, generate))(struct ccrng_state *rng, size_t outlen, void *out);
19
20/*!
21 @type struct ccrng_state
22 @abstract Default state structure. Do not instantiate. ccrng() returns a reference to this structure
23 */
24struct ccrng_state {
25 CCRNG_STATE_COMMON
26};
27
28/*!
29 @function ccrng
30 @abstract Get a handle to a secure RNG
31
32 @param error A pointer to set in case of error; may be null
33
34 @result A handle to a secure RNG, or null if one cannot be initialized successfully
35
36 @discussion
37 This function returns a pointer to the most appropriate RNG for the
38 environment. This may be a TRNG if one is available. Otherwise, it is
39 a PRNG offering several features:
40 - Good performance
41 - FIPS Compliant: NIST SP800-90A + FIPS 140-2
42 - Seeded from the appropriate entropy source for the platform
43 - Provides at least 128-bit security
44 - Backtracing resistance
45 - Prediction break (after reseed)
46 */
47struct ccrng_state *ccrng(int *error);
48
49/*!
50 @function ccrng_generate
51 @abstract Generate `outlen` bytes of output, stored in `out`, using ccrng_state `rng`.
52
53 @param rng `struct ccrng_state` representing the state of the RNG.
54 @param outlen Amount of random bytes to generate.
55 @param out Pointer to memory where random bytes are stored, of size at least `outlen`.
56
57 @result 0 on success and nonzero on failure.
58 */
59#define ccrng_generate(rng, outlen, out) \
60 ((rng)->generate((struct ccrng_state *)(rng), (outlen), (out)))
61
62#if !CC_EXCLAVEKIT
63/*!
64 @function ccrng_uniform
65 @abstract Generate a random value in @p [0, bound).
66
67 @param rng The state of the RNG.
68 @param bound The exclusive upper bound on the output.
69 @param rand A pointer to a single @p uint64_t to store the result.
70
71 @result Returns zero iff the operation is successful.
72 */
73int ccrng_uniform(struct ccrng_state *rng, uint64_t bound, uint64_t *rand);
74#endif
75
76#endif /* _CORECRYPTO_CCRNG_H_ */
77