From d539be33590f7dfb0013187502744286f2959ee3 Mon Sep 17 00:00:00 2001 From: moneromooo-monero Date: Sat, 14 May 2016 22:08:10 +0100 Subject: [PATCH] crypto: make clear generate_random_bytes is not thread safe And add a thread safe version to encourage proper use --- src/crypto/crypto.cpp | 2 +- src/crypto/crypto.h | 9 ++++++++- src/crypto/random.c | 2 +- src/crypto/random.h | 2 +- 4 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/crypto/crypto.cpp b/src/crypto/crypto.cpp index e47aab0f..e251d0ec 100644 --- a/src/crypto/crypto.cpp +++ b/src/crypto/crypto.cpp @@ -83,7 +83,7 @@ namespace crypto { /* generate a random 32-byte (256-bit) integer and copy it to res */ static inline void random_scalar(ec_scalar &res) { unsigned char tmp[64]; - generate_random_bytes(64, tmp); + generate_random_bytes_not_thread_safe(64, tmp); sc_reduce(tmp); memcpy(&res, tmp, 32); } diff --git a/src/crypto/crypto.h b/src/crypto/crypto.h index 883aa521..fa55c2aa 100644 --- a/src/crypto/crypto.h +++ b/src/crypto/crypto.h @@ -117,13 +117,20 @@ namespace crypto { const public_key *const *, std::size_t, const signature *); }; + /* Generate N random bytes + */ + inline void rand(size_t N, uint8_t *bytes) { + boost::lock_guard lock(random_lock); + generate_random_bytes_not_thread_safe(N, bytes); + } + /* Generate a value filled with random bytes. */ template typename std::enable_if::value, T>::type rand() { typename std::remove_cv::type res; boost::lock_guard lock(random_lock); - generate_random_bytes(sizeof(T), &res); + generate_random_bytes_not_thread_safe(sizeof(T), &res); return res; } diff --git a/src/crypto/random.c b/src/crypto/random.c index f8a50d85..6a9f63c1 100644 --- a/src/crypto/random.c +++ b/src/crypto/random.c @@ -113,7 +113,7 @@ INITIALIZER(init_random) { #endif } -void generate_random_bytes(size_t n, void *result) { +void generate_random_bytes_not_thread_safe(size_t n, void *result) { #if !defined(NDEBUG) assert(curstate == 1); curstate = 2; diff --git a/src/crypto/random.h b/src/crypto/random.h index 322b5bad..b0d2303b 100644 --- a/src/crypto/random.h +++ b/src/crypto/random.h @@ -32,4 +32,4 @@ #include -void generate_random_bytes(size_t n, void *result); +void generate_random_bytes_not_thread_safe(size_t n, void *result);