diff --git a/data/FixedSizeData.h b/data/FixedSizeData.h index 4fbbced3..fb92b69f 100644 --- a/data/FixedSizeData.h +++ b/data/FixedSizeData.h @@ -7,6 +7,7 @@ #include #include #include "../assert/assert.h" +#include "ThreadsafePseudoRandomPool.h" namespace cpputils { @@ -34,7 +35,7 @@ public: private: FixedSizeData() {} - static CryptoPP::AutoSeededRandomPool &PseudoRandomPool(); + static ThreadsafePseudoRandomPool &PseudoRandomPool(); unsigned char _data[BINARY_LENGTH]; }; @@ -48,9 +49,8 @@ template constexpr unsigned int FixedSizeData::BINARY_L template constexpr unsigned int FixedSizeData::STRING_LENGTH; template -CryptoPP::AutoSeededRandomPool &FixedSizeData::PseudoRandomPool() { - //TODO Make seeding use blocking=true (aka /dev/random instead of /dev/urandom) or offer a configuration option? - static CryptoPP::AutoSeededRandomPool singleton; +ThreadsafePseudoRandomPool &FixedSizeData::PseudoRandomPool() { + static ThreadsafePseudoRandomPool singleton; return singleton; } diff --git a/data/ThreadsafePseudoRandomPool.h b/data/ThreadsafePseudoRandomPool.h new file mode 100644 index 00000000..e6d5c564 --- /dev/null +++ b/data/ThreadsafePseudoRandomPool.h @@ -0,0 +1,34 @@ +#pragma once +#ifndef MESSMER_CPPUTILS_DATA_THREADSAFEPSEUDORANDOMPOOL_H +#define MESSMER_CPPUTILS_DATA_THREADSAFEPSEUDORANDOMPOOL_H + +#include "../macros.h" + +namespace cpputils { + + //TODO Store a static CryptoPP::AutoSeededRandomPool (or multiple ones) and make constructor of + // ThreadsafeRandomPool() be lightweight (i.e. not do seeding), so it can be called on each callsite. + // Alternatively, use a singleton factory. + + //TODO Test + class ThreadsafePseudoRandomPool { + public: + ThreadsafePseudoRandomPool() { } + + void GenerateBlock(byte *data, size_t size) { + // TODO Provide multiple randomPools for parallelity instead of locking the only available one + std::unique_lock lock(_mutex); + _pool.GenerateBlock(data, size); + } + + private: + //TODO Make seeding use blocking=true (aka /dev/random instead of /dev/urandom) or offer a configuration option? + CryptoPP::AutoSeededRandomPool _pool; + std::mutex _mutex; + + DISALLOW_COPY_AND_ASSIGN(ThreadsafePseudoRandomPool); + }; + +} + +#endif