Skip to content

Commit 97477c5

Browse files
committed
Maintain state across GetStrongRandBytes calls
1 parent 35da2ae commit 97477c5

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

src/random.cpp

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@
3232
#include <sys/sysctl.h>
3333
#endif
3434

35+
#include <mutex>
36+
3537
#include <openssl/err.h>
3638
#include <openssl/rand.h>
3739

@@ -192,6 +194,10 @@ void GetRandBytes(unsigned char* buf, int num)
192194
}
193195
}
194196

197+
static std::mutex cs_rng_state;
198+
static unsigned char rng_state[32] = {0};
199+
static uint64_t rng_counter = 0;
200+
195201
void GetStrongRandBytes(unsigned char* out, int num)
196202
{
197203
assert(num <= 32);
@@ -207,8 +213,17 @@ void GetStrongRandBytes(unsigned char* out, int num)
207213
GetOSRand(buf);
208214
hasher.Write(buf, 32);
209215

216+
// Combine with and update state
217+
{
218+
std::unique_lock<std::mutex> lock(cs_rng_state);
219+
hasher.Write(rng_state, sizeof(rng_state));
220+
hasher.Write((const unsigned char*)&rng_counter, sizeof(rng_counter));
221+
++rng_counter;
222+
hasher.Finalize(buf);
223+
memcpy(rng_state, buf + 32, 32);
224+
}
225+
210226
// Produce output
211-
hasher.Finalize(buf);
212227
memcpy(out, buf, num);
213228
memory_cleanse(buf, 64);
214229
}

0 commit comments

Comments
 (0)