2 * Copyright 2019 The OpenSSL Project Authors. All Rights Reserved.
3 * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
5 * Licensed under the Apache License 2.0 (the "License"). You may not use
6 * this file except in compliance with the License. You can obtain a copy
7 * in the file LICENSE in the source distribution or at
8 * https://www.openssl.org/source/license.html
12 * Implementation of the FIPS 140-2 section 4.9.2 Conditional Tests.
16 #include <openssl/evp.h>
17 #include "internal/rand_int.h"
18 #include "internal/thread_once.h"
21 static RAND_POOL *crngt_pool;
22 static unsigned char crngt_prev[EVP_MAX_MD_SIZE];
24 int (*crngt_get_entropy)(unsigned char *, unsigned char *, unsigned int *)
25 = &rand_crngt_get_entropy_cb;
27 int rand_crngt_get_entropy_cb(unsigned char *buf, unsigned char *md,
28 unsigned int *md_size)
34 n = rand_pool_acquire_entropy(crngt_pool);
35 if (n >= CRNGT_BUFSIZ) {
36 p = rand_pool_detach(crngt_pool);
37 r = EVP_Digest(p, CRNGT_BUFSIZ, md, md_size, EVP_sha256(), NULL);
39 memcpy(buf, p, CRNGT_BUFSIZ);
40 rand_pool_reattach(crngt_pool, p);
46 void rand_crngt_cleanup(void)
48 rand_pool_free(crngt_pool);
52 int rand_crngt_init(void)
54 unsigned char buf[CRNGT_BUFSIZ];
56 if ((crngt_pool = rand_pool_new(0, CRNGT_BUFSIZ, CRNGT_BUFSIZ)) == NULL)
58 if (crngt_get_entropy(buf, crngt_prev, NULL)) {
59 OPENSSL_cleanse(buf, sizeof(buf));
66 static CRYPTO_ONCE rand_crngt_init_flag = CRYPTO_ONCE_STATIC_INIT;
67 DEFINE_RUN_ONCE_STATIC(do_rand_crngt_init)
69 return OPENSSL_init_crypto(0, NULL)
71 && OPENSSL_atexit(&rand_crngt_cleanup);
74 int rand_crngt_single_init(void)
76 return RUN_ONCE(&rand_crngt_init_flag, do_rand_crngt_init);
79 size_t rand_crngt_get_entropy(RAND_DRBG *drbg,
81 int entropy, size_t min_len, size_t max_len,
82 int prediction_resistance)
84 unsigned char buf[CRNGT_BUFSIZ], md[EVP_MAX_MD_SIZE];
87 size_t q, r = 0, s, t = 0;
90 if (!RUN_ONCE(&rand_crngt_init_flag, do_rand_crngt_init))
93 if ((pool = rand_pool_new(entropy, min_len, max_len)) == NULL)
96 while ((q = rand_pool_bytes_needed(pool, 1)) > 0 && attempts-- > 0) {
97 s = q > sizeof(buf) ? sizeof(buf) : q;
98 if (!crngt_get_entropy(buf, md, &sz)
99 || memcmp(crngt_prev, md, sz) == 0
100 || !rand_pool_add(pool, buf, s, s * 8))
102 memcpy(crngt_prev, md, sz);
107 *pout = rand_pool_detach(pool);
109 OPENSSL_cleanse(buf, sizeof(buf));
110 rand_pool_free(pool);
114 void rand_crngt_cleanup_entropy(RAND_DRBG *drbg,
115 unsigned char *out, size_t outlen)
117 OPENSSL_secure_clear_free(out, outlen);