From a2195b9b7fba5da7f47903961db3fb31f6d7146c Mon Sep 17 00:00:00 2001 From: stoffu Date: Wed, 3 Apr 2019 14:10:24 +0900 Subject: crypto: replace rand()%N idiom with unbiased rand_idx(N) --- src/crypto/crypto.h | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) (limited to 'src/crypto/crypto.h') diff --git a/src/crypto/crypto.h b/src/crypto/crypto.h index 22b182ab0..bac456f60 100644 --- a/src/crypto/crypto.h +++ b/src/crypto/crypto.h @@ -35,6 +35,7 @@ #include #include #include +#include #include "common/pod-class.h" #include "memwipe.h" @@ -162,6 +163,32 @@ namespace crypto { return res; } + /* UniformRandomBitGenerator using crypto::rand() + */ + struct random_device + { + typedef uint64_t result_type; + static constexpr result_type min() { return 0; } + static constexpr result_type max() { return result_type(-1); } + result_type operator()() const { return crypto::rand(); } + }; + + /* Generate a random value between range_min and range_max + */ + template + typename std::enable_if::value, T>::type rand_range(T range_min, T range_max) { + crypto::random_device rd; + std::uniform_int_distribution dis(range_min, range_max); + return dis(rd); + } + + /* Generate a random index between 0 and sz-1 + */ + template + typename std::enable_if::value, T>::type rand_idx(T sz) { + return crypto::rand_range(0, sz-1); + } + /* Generate a new key pair */ inline secret_key generate_keys(public_key &pub, secret_key &sec, const secret_key& recovery_key = secret_key(), bool recover = false) { -- cgit v1.2.3