Random::add_seed

GitOrigin-RevId: 23546ee0d4c6c9287226e8a12b7ab37ac7e5bede
This commit is contained in:
Arseny Smirnov 2018-03-26 17:01:27 +03:00
parent 26b5c231a6
commit 597db4b4ce
2 changed files with 14 additions and 1 deletions

View File

@ -20,12 +20,15 @@
namespace td { namespace td {
#if TD_HAVE_OPENSSL #if TD_HAVE_OPENSSL
namespace {
constexpr size_t secure_bytes_buffer_size = 512;
}
void Random::secure_bytes(MutableSlice dest) { void Random::secure_bytes(MutableSlice dest) {
Random::secure_bytes(dest.ubegin(), dest.size()); Random::secure_bytes(dest.ubegin(), dest.size());
} }
void Random::secure_bytes(unsigned char *ptr, size_t size) { void Random::secure_bytes(unsigned char *ptr, size_t size) {
constexpr size_t buf_size = 512; constexpr size_t buf_size = secure_bytes_buffer_size;
static TD_THREAD_LOCAL unsigned char *buf; // static zero-initialized static TD_THREAD_LOCAL unsigned char *buf; // static zero-initialized
static TD_THREAD_LOCAL size_t buf_pos; static TD_THREAD_LOCAL size_t buf_pos;
if (init_thread_local<unsigned char[]>(buf, buf_size)) { if (init_thread_local<unsigned char[]>(buf, buf_size)) {
@ -68,6 +71,13 @@ int64 Random::secure_int64() {
secure_bytes(reinterpret_cast<unsigned char *>(&res), sizeof(int64)); secure_bytes(reinterpret_cast<unsigned char *>(&res), sizeof(int64));
return res; return res;
} }
void Random::add_seed(Slice bytes, double entropy) {
RAND_add(bytes.data(), static_cast<int>(bytes.size()), entropy);
// drain all secure_bytes buffer
std::array<char, secure_bytes_buffer_size> buf;
secure_bytes(MutableSlice(buf.data(), buf.size()));
}
#endif #endif
static unsigned int rand_device_helper() { static unsigned int rand_device_helper() {

View File

@ -18,6 +18,9 @@ class Random {
static void secure_bytes(unsigned char *ptr, size_t size); static void secure_bytes(unsigned char *ptr, size_t size);
static int32 secure_int32(); static int32 secure_int32();
static int64 secure_int64(); static int64 secure_int64();
// works only for current thread
static void add_seed(Slice bytes, double entropy = 0);
#endif #endif
static uint32 fast_uint32(); static uint32 fast_uint32();