2
This file is part of TON Blockchain Library.
4
TON Blockchain Library is free software: you can redistribute it and/or modify
5
it under the terms of the GNU Lesser General Public License as published by
6
the Free Software Foundation, either version 2 of the License, or
7
(at your option) any later version.
9
TON Blockchain Library is distributed in the hope that it will be useful,
10
but WITHOUT ANY WARRANTY; without even the implied warranty of
11
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
GNU Lesser General Public License for more details.
14
You should have received a copy of the GNU Lesser General Public License
15
along with TON Blockchain Library. If not, see <http://www.gnu.org/licenses/>.
17
Copyright 2017-2020 Telegram Systems LLP
19
#include "openssl/rand.hpp"
21
#include "td/utils/common.h"
23
#include <openssl/rand.h>
24
#include <openssl/opensslv.h>
27
int os_get_random_bytes(void *buf, int n);
29
bool RandomGen::ok() const {
33
void RandomGen::seed_add(const void *data, std::size_t size, double entropy) {
34
RAND_add(data, static_cast<int>(size), entropy > 0 ? entropy : static_cast<double>(size));
37
void RandomGen::randomize(bool force) {
41
unsigned char buffer[128];
42
int n = os_get_random_bytes(buffer, 128);
47
bool RandomGen::rand_bytes(void *data, std::size_t size, bool strong) {
48
#if OPENSSL_VERSION_NUMBER < 0x10101000L
49
int res = (strong ? RAND_bytes : RAND_pseudo_bytes)((unsigned char *)data, static_cast<int>(size));
51
int res = RAND_bytes((unsigned char *)data, static_cast<int>(size));
53
if (res != 0 && res != 1) {
59
std::string RandomGen::rand_string(std::size_t size, bool strong) {
60
std::string result(size, '\0');
61
if (size > 0 && !rand_bytes(&result[0], size, strong)) {
67
RandomGen &rand_gen() {
68
// RandomGen is stateless, OpenSSL will handle concurrent access
69
static RandomGen MainPRNG;
74
//------------------------- move to separate OS-dependent file?
77
int os_get_random_bytes(void *buf, int n) {
87
int os_get_random_bytes(void *buf, int n) {
90
int h = open("/dev/random", O_RDONLY | O_NONBLOCK);
92
r = static_cast<int>(read(h, buf, n));
94
//std::cerr << "added " << r << " bytes of real entropy to secure random numbers seed" << std::endl;
102
h = open("/dev/urandom", O_RDONLY);
106
int s = static_cast<int>(read(h, (char *)buf + r, n - r));
115
*(long *)buf ^= lrand48();
116
srand48(*(long *)buf);