2 * Copyright 2020-2023 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
10 #include "rand_local.h"
11 #include "crypto/rand.h"
12 #include "crypto/rand_pool.h"
13 #include "internal/core.h"
14 #include <openssl/core_dispatch.h>
15 #include <openssl/err.h>
17 size_t ossl_rand_get_entropy(ossl_unused OSSL_LIB_CTX *ctx,
18 unsigned char **pout, int entropy,
19 size_t min_len, size_t max_len)
22 size_t entropy_available;
25 pool = ossl_rand_pool_new(entropy, 1, min_len, max_len);
27 ERR_raise(ERR_LIB_RAND, ERR_R_RAND_LIB);
31 /* Get entropy by polling system entropy sources. */
32 entropy_available = ossl_pool_acquire_entropy(pool);
34 if (entropy_available > 0) {
35 ret = ossl_rand_pool_length(pool);
36 *pout = ossl_rand_pool_detach(pool);
39 ossl_rand_pool_free(pool);
43 size_t ossl_rand_get_user_entropy(OSSL_LIB_CTX *ctx,
44 unsigned char **pout, int entropy,
45 size_t min_len, size_t max_len)
48 EVP_RAND_CTX *rng = ossl_rand_get0_seed_noncreating(ctx);
52 return ossl_rand_get_entropy(ctx, pout, entropy, min_len, max_len);
54 /* Determine how many bytes to generate */
55 ret = entropy > 0 ? (size_t)(7 + entropy) / 8 : min_len;
58 else if (ret > max_len)
61 /* Allocate the return buffer */
62 if ((buf = OPENSSL_secure_malloc(ret)) == NULL)
66 if (!EVP_RAND_generate(rng, buf, ret, entropy, 0, NULL, 0)) {
74 void ossl_rand_cleanup_entropy(ossl_unused OSSL_LIB_CTX *ctx,
75 unsigned char *buf, size_t len)
77 OPENSSL_secure_clear_free(buf, len);
80 size_t ossl_rand_get_nonce(ossl_unused OSSL_LIB_CTX *ctx,
82 size_t min_len, ossl_unused size_t max_len,
83 const void *salt, size_t salt_len)
88 pool = ossl_rand_pool_new(0, 0, min_len, max_len);
90 ERR_raise(ERR_LIB_RAND, ERR_R_RAND_LIB);
94 if (!ossl_pool_add_nonce_data(pool))
97 if (salt != NULL && !ossl_rand_pool_add(pool, salt, salt_len, 0))
99 ret = ossl_rand_pool_length(pool);
100 *pout = ossl_rand_pool_detach(pool);
102 ossl_rand_pool_free(pool);
106 size_t ossl_rand_get_user_nonce(OSSL_LIB_CTX *ctx,
107 unsigned char **pout,
108 size_t min_len, size_t max_len,
109 const void *salt, size_t salt_len)
112 EVP_RAND_CTX *rng = ossl_rand_get0_seed_noncreating(ctx);
115 return ossl_rand_get_nonce(ctx, pout, min_len, max_len, salt, salt_len);
117 if ((buf = OPENSSL_malloc(min_len)) == NULL)
120 if (!EVP_RAND_generate(rng, buf, min_len, 0, 0, salt, salt_len)) {
128 void ossl_rand_cleanup_nonce(ossl_unused OSSL_LIB_CTX *ctx,
129 unsigned char *buf, size_t len)
131 OPENSSL_clear_free(buf, len);