From 4703264c5754290f58e4ff7361a28d3f47dc49e9 Mon Sep 17 00:00:00 2001 From: Reece Date: Fri, 1 Oct 2021 17:54:55 +0100 Subject: [PATCH] [+] Added 64bit rng seed support [*] Cryptographically unsafe RNG is marginally less dangerous; use secure rng for the entire base seed instead of seeding using 32bit mt --- Include/Aurora/RNG/IRandomDevice.hpp | 9 ++++++++- Source/RNG/RandomDevice.cpp | 14 +++++++++++++- Source/RNG/WELL.cpp | 19 +++++++++++++++++++ Source/RNG/WELL.hpp | 1 + 4 files changed, 41 insertions(+), 2 deletions(-) diff --git a/Include/Aurora/RNG/IRandomDevice.hpp b/Include/Aurora/RNG/IRandomDevice.hpp index f84788fe..a02a32dd 100644 --- a/Include/Aurora/RNG/IRandomDevice.hpp +++ b/Include/Aurora/RNG/IRandomDevice.hpp @@ -64,13 +64,20 @@ namespace Aurora::RNG { bool secure; AuOptional seed; - + AuOptional seed64; + inline void SetSeed(AuUInt32 seed) { this->seed = seed; this->secure = false; } + inline void SetSeed64(AuUInt64 seed) + { + this->seed64 = seed; + this->secure = false; + } + inline void SetCSRNG() { this->secure = true; diff --git a/Source/RNG/RandomDevice.cpp b/Source/RNG/RandomDevice.cpp index 0b811e96..bd44c76c 100644 --- a/Source/RNG/RandomDevice.cpp +++ b/Source/RNG/RandomDevice.cpp @@ -40,7 +40,19 @@ namespace Aurora::RNG this->def_ = def; if (!def.secure) { - this->fast_ = WELL_SeedRand(def.seed.value_or(Aurora::RNG::RngTmpl())); + if (def.seed) + { + this->fast_ = WELL_SeedRand(def.seed.value()); + } + else if (def.seed64) + { + this->fast_ = WELL_SeedRand64(def.seed64.value()); + } + else + { + this->fast_ = {}; + RNG::RngArray(this->fast_.state); + } } } diff --git a/Source/RNG/WELL.cpp b/Source/RNG/WELL.cpp index 3b614e3c..b0ac7db9 100644 --- a/Source/RNG/WELL.cpp +++ b/Source/RNG/WELL.cpp @@ -26,6 +26,18 @@ inline static void WELL_SeedRand(WELLRand *rand, AuUInt32 seed) } } +inline static void WELL_SeedRand64(WELLRand *rand, AuUInt64 seed) +{ + MTRand mtrand = MT_SeedRand(seed & 0xffffffff); + MTRand mtrand2 = MT_SeedRand(seed >> 32); + + for (unsigned int i = 0; i < 16; i += 2) + { + rand->state[i] = MT_NextLong(&mtrand); + rand->state[i + 1] = MT_NextLong(&mtrand2); + } +} + /** * Creates a new random number generator from a given seed. */ @@ -36,6 +48,13 @@ WELLRand WELL_SeedRand(AuUInt32 seed) return rand; } +WELLRand WELL_SeedRand64(AuUInt64 seed) +{ + WELLRand rand {}; + WELL_SeedRand64(&rand, seed); + return rand; +} + /** * Generates a pseudo-randomly generated long. */ diff --git a/Source/RNG/WELL.hpp b/Source/RNG/WELL.hpp index 5b782f1d..94959778 100644 --- a/Source/RNG/WELL.hpp +++ b/Source/RNG/WELL.hpp @@ -8,5 +8,6 @@ struct WELLRand }; WELLRand WELL_SeedRand(AuUInt32 seed); +WELLRand WELL_SeedRand64(AuUInt64 seed); AuUInt32 WELL_NextLong(WELLRand* rand); void WELL_NextBytes(WELLRand *rand, void *in, AuUInt32 length); \ No newline at end of file