From 8335db4db5556e918d5e8a321944d3b16d32f638 Mon Sep 17 00:00:00 2001 From: Felix Geyer Date: Fri, 8 Jul 2011 14:40:42 +0200 Subject: [PATCH] Add Random::randomUInt() and Random::randomUIntRange(). --- src/crypto/Random.cpp | 19 ++++++++++++++++++- src/crypto/Random.h | 11 +++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/crypto/Random.cpp b/src/crypto/Random.cpp index 0d6d77168..d84106ec0 100644 --- a/src/crypto/Random.cpp +++ b/src/crypto/Random.cpp @@ -21,7 +21,7 @@ void Random::randomize(QByteArray& ba) { - gcry_randomize(ba.data(), ba.size(), GCRY_STRONG_RANDOM); + randomize(ba.data(), ba.size()); } QByteArray Random::randomArray(int len) @@ -34,6 +34,23 @@ QByteArray Random::randomArray(int len) return ba; } +quint32 Random::randomUInt(quint32 limit) +{ + quint32 rand; + randomize(&rand, 4); + return (rand % limit); +} + +quint32 Random::randomUIntRange(quint32 min, quint32 max) +{ + return min + randomUInt(max - min); +} + +void Random::randomize(void* data, int len) +{ + gcry_randomize(data, len, GCRY_STRONG_RANDOM); +} + Random::Random() { } diff --git a/src/crypto/Random.h b/src/crypto/Random.h index a93f5a3c7..987ba6fd7 100644 --- a/src/crypto/Random.h +++ b/src/crypto/Random.h @@ -26,7 +26,18 @@ public: static void randomize(QByteArray& ba); static QByteArray randomArray(int len); + /** + * Generate a random quint32 in the range [0, @p limit) + */ + static quint32 randomUInt(quint32 limit); + + /** + * Generate a random quint32 in the range [@p min, @p max) + */ + static quint32 randomUIntRange(quint32 min, quint32 max); + private: + static void randomize(void* data, int len); Random(); };