2 * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (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
12 #include "internal/cryptlib.h"
13 #include <openssl/opensslconf.h>
14 #include "internal/rand.h"
16 #include <openssl/engine.h>
18 #ifndef OPENSSL_NO_ENGINE
19 /* non-NULL if default_RAND_meth is ENGINE-provided */
20 static ENGINE *funct_ref = NULL;
22 static const RAND_METHOD *default_RAND_meth = NULL;
24 int RAND_set_rand_method(const RAND_METHOD *meth)
26 #ifndef OPENSSL_NO_ENGINE
27 ENGINE_finish(funct_ref);
30 default_RAND_meth = meth;
34 const RAND_METHOD *RAND_get_rand_method(void)
36 if (!default_RAND_meth) {
37 #ifndef OPENSSL_NO_ENGINE
38 ENGINE *e = ENGINE_get_default_RAND();
40 default_RAND_meth = ENGINE_get_RAND(e);
41 if (default_RAND_meth == NULL) {
50 default_RAND_meth = RAND_OpenSSL();
52 return default_RAND_meth;
55 #ifndef OPENSSL_NO_ENGINE
56 int RAND_set_rand_engine(ENGINE *engine)
58 const RAND_METHOD *tmp_meth = NULL;
60 if (!ENGINE_init(engine))
62 tmp_meth = ENGINE_get_RAND(engine);
63 if (tmp_meth == NULL) {
64 ENGINE_finish(engine);
68 /* This function releases any prior ENGINE so call it first */
69 RAND_set_rand_method(tmp_meth);
75 void rand_cleanup_int(void)
77 const RAND_METHOD *meth = RAND_get_rand_method();
78 if (meth && meth->cleanup)
80 RAND_set_rand_method(NULL);
83 void RAND_seed(const void *buf, int num)
85 const RAND_METHOD *meth = RAND_get_rand_method();
86 if (meth && meth->seed)
90 void RAND_add(const void *buf, int num, double entropy)
92 const RAND_METHOD *meth = RAND_get_rand_method();
93 if (meth && meth->add)
94 meth->add(buf, num, entropy);
97 int RAND_bytes(unsigned char *buf, int num)
99 const RAND_METHOD *meth = RAND_get_rand_method();
100 if (meth && meth->bytes)
101 return meth->bytes(buf, num);
105 #if OPENSSL_API_COMPAT < 0x10100000L
106 int RAND_pseudo_bytes(unsigned char *buf, int num)
108 const RAND_METHOD *meth = RAND_get_rand_method();
109 if (meth && meth->pseudorand)
110 return meth->pseudorand(buf, num);
115 int RAND_status(void)
117 const RAND_METHOD *meth = RAND_get_rand_method();
118 if (meth && meth->status)
119 return meth->status();