mirror of
https://github.com/monero-project/monero.git
synced 2025-08-23 07:05:08 -04:00
crypto: replace rand<T>()%N idiom with unbiased rand_idx(N)
This commit is contained in:
parent
b6726aaa6c
commit
a2195b9b7f
5 changed files with 36 additions and 12 deletions
|
@ -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) {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue