From 674ceedc4a18457718c710986f4c1b9a518963fc Mon Sep 17 00:00:00 2001 From: surtur Date: Thu, 20 Jan 2022 08:36:02 +0100 Subject: [PATCH] gen: mtx -> mutable recursive_mtx to all functions --- generator.cpp | 16 ++++++++++++++-- generator.h | 3 ++- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/generator.cpp b/generator.cpp index 9208a6b..3e7526b 100644 --- a/generator.cpp +++ b/generator.cpp @@ -34,6 +34,8 @@ Generator::~Generator() noexcept {} void Generator::initialize_generator() { + std::lock_guard lg(mtx); + try { std::memset(G.k, 0x00, G.k.size()); G.ctr = 0; @@ -46,6 +48,8 @@ void Generator::initialize_generator() { } auto Generator::get_state() const -> G_state { + std::lock_guard lg(mtx); + return G; } @@ -54,6 +58,8 @@ auto Generator::time_to_reseed( const unsigned int& min_p_size, const std::chrono::duration>& time_elapsed, const std::chrono::milliseconds& gen_reseed_interval) const -> bool { + std::lock_guard lg(mtx); + if (pool0_len >= min_p_size && time_elapsed > gen_reseed_interval) { return true; } @@ -63,7 +69,9 @@ auto Generator::time_to_reseed( } auto Generator::reseed(const std::string& s) -> void { + std::lock_guard lg(mtx); std::unique_lock ul(reseed_mtx); + // ref: https://www.cryptopp.com/wiki/SecBlock std::string da_key(reinterpret_cast(&G.k[0]), G.k.SizeInBytes() * 8); // we need the size in bits @@ -84,6 +92,8 @@ auto Generator::do_crypto() -> std::string { * returns a string of k*(16 bytes); * do whatever atm */ + std::lock_guard lg(mtx); + // for the moment loosely based on // https://www.cryptopp.com/wiki/CTR_Mode @@ -101,7 +111,6 @@ auto Generator::do_crypto() -> std::string { try { CryptoPP::CTR_Mode::Encryption e; e.SetKeyWithIV(G.k, G.k.size(), ctr); - ul.unlock(); // The StreamTransformationFilter adds padding as required. ECB and // CBC Mode must be padded to the block size of the cipher. CTR @@ -133,6 +142,8 @@ auto Generator::do_crypto() -> std::string { } auto Generator::generate_blocks(unsigned int k_blocks) -> std::string { + std::lock_guard lg(mtx); + assert((G.ctr != 0) && "Counter is not 0, generator has been seeded"); std::string r{""}; @@ -144,7 +155,8 @@ auto Generator::generate_blocks(unsigned int k_blocks) -> std::string { } auto Generator::generate_random_data(const unsigned int& n) -> std::string { - std::lock_guard lg(mtx); + std::lock_guard lg(mtx); + if (n == 0) { // do not do this..? const std::string msg{"zero bytes requested, bailing\n"}; diff --git a/generator.h b/generator.h index ac7ca62..7f8bd71 100644 --- a/generator.h +++ b/generator.h @@ -15,7 +15,7 @@ namespace generator { class Generator { public: std::chrono::milliseconds reseed_interval{100}; - std::mutex mtx; + mutable std::recursive_mutex mtx; std::mutex crypt_mtx; std::mutex reseed_mtx; @@ -36,6 +36,7 @@ public: const std::chrono::milliseconds& reseed_interval) const -> bool; auto is_seeded() const -> bool { + std::lock_guard lg(mtx); return !(this->G.ctr == 0x00); }