xref: /openssl/crypto/rand/rand_meth.c (revision dce7272d)
1 /*
2  * Copyright 2011-2021 The OpenSSL Project Authors. All Rights Reserved.
3  *
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
8  */
9 
10 #include <openssl/evp.h>
11 #include <openssl/rand.h>
12 #include "rand_local.h"
13 
14 /* Implements the default OpenSSL RAND_add() method */
drbg_add(const void * buf,int num,double randomness)15 static int drbg_add(const void *buf, int num, double randomness)
16 {
17     EVP_RAND_CTX *drbg = RAND_get0_primary(NULL);
18 
19     if (drbg == NULL || num <= 0)
20         return 0;
21 
22     return EVP_RAND_reseed(drbg, 0, NULL, 0, buf, num);
23 }
24 
25 /* Implements the default OpenSSL RAND_seed() method */
drbg_seed(const void * buf,int num)26 static int drbg_seed(const void *buf, int num)
27 {
28     return drbg_add(buf, num, num);
29 }
30 
31 /* Implements the default OpenSSL RAND_status() method */
drbg_status(void)32 static int drbg_status(void)
33 {
34     EVP_RAND_CTX *drbg = RAND_get0_primary(NULL);
35 
36     if (drbg == NULL)
37         return 0;
38 
39     return  EVP_RAND_get_state(drbg) == EVP_RAND_STATE_READY ? 1 : 0;
40 }
41 
42 /* Implements the default OpenSSL RAND_bytes() method */
drbg_bytes(unsigned char * out,int count)43 static int drbg_bytes(unsigned char *out, int count)
44 {
45     EVP_RAND_CTX *drbg = RAND_get0_public(NULL);
46 
47     if (drbg == NULL)
48         return 0;
49 
50     return EVP_RAND_generate(drbg, out, count, 0, 0, NULL, 0);
51 }
52 
53 RAND_METHOD ossl_rand_meth = {
54     drbg_seed,
55     drbg_bytes,
56     NULL,
57     drbg_add,
58     drbg_bytes,
59     drbg_status
60 };
61 
RAND_OpenSSL(void)62 RAND_METHOD *RAND_OpenSSL(void)
63 {
64     return &ossl_rand_meth;
65 }
66