diff options
author | Riccardo Spagni <ric@spagni.net> | 2019-04-15 09:14:28 +0200 |
---|---|---|
committer | Riccardo Spagni <ric@spagni.net> | 2019-04-15 09:14:28 +0200 |
commit | 89b8ecfc7c88510681b6d354586e68510c150cda (patch) | |
tree | bd3ae35111a04d726f85fa2f9e2e36da0f23a51a /src/crypto | |
parent | Merge pull request #5369 (diff) | |
parent | crypto: replace rand<T>()%N idiom with unbiased rand_idx(N) (diff) | |
download | monero-89b8ecfc7c88510681b6d354586e68510c150cda.tar.xz |
Merge pull request #5392
a2195b9b crypto: replace rand<T>()%N idiom with unbiased rand_idx(N) (stoffu)
Diffstat (limited to 'src/crypto')
-rw-r--r-- | src/crypto/crypto.h | 27 |
1 files changed, 27 insertions, 0 deletions
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 <boost/optional.hpp> #include <type_traits> #include <vector> +#include <random> #include "common/pod-class.h" #include "memwipe.h" @@ -162,6 +163,32 @@ namespace crypto { return res; } + /* UniformRandomBitGenerator using crypto::rand<uint64_t>() + */ + 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<result_type>(); } + }; + + /* Generate a random value between range_min and range_max + */ + template<typename T> + typename std::enable_if<std::is_integral<T>::value, T>::type rand_range(T range_min, T range_max) { + crypto::random_device rd; + std::uniform_int_distribution<T> dis(range_min, range_max); + return dis(rd); + } + + /* Generate a random index between 0 and sz-1 + */ + template<typename T> + typename std::enable_if<std::is_unsigned<T>::value, T>::type rand_idx(T sz) { + return crypto::rand_range<T>(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) { |