| 316 | } |
| 317 | |
| 318 | void GetStrongRandBytes(unsigned char* out, int num) |
| 319 | { |
| 320 | assert(num <= 32); |
| 321 | CSHA512 hasher; |
| 322 | unsigned char buf[64]; |
| 323 | |
| 324 | // First source: OpenSSL's RNG |
| 325 | RandAddSeedPerfmon(); |
| 326 | GetRandBytes(buf, 32); |
| 327 | hasher.Write(buf, 32); |
| 328 | |
| 329 | // Second source: OS RNG |
| 330 | GetOSRand(buf); |
| 331 | hasher.Write(buf, 32); |
| 332 | |
| 333 | // Third source: HW RNG, if available. |
| 334 | if (GetHWRand(buf)) { |
| 335 | hasher.Write(buf, 32); |
| 336 | } |
| 337 | |
| 338 | // Combine with and update state |
| 339 | { |
| 340 | std::unique_lock<std::mutex> lock(cs_rng_state); |
| 341 | hasher.Write(rng_state, sizeof(rng_state)); |
| 342 | hasher.Write((const unsigned char*)&rng_counter, sizeof(rng_counter)); |
| 343 | ++rng_counter; |
| 344 | hasher.Finalize(buf); |
| 345 | memcpy(rng_state, buf + 32, 32); |
| 346 | } |
| 347 | |
| 348 | // Produce output |
| 349 | memcpy(out, buf, num); |
| 350 | memory_cleanse(buf, 64); |
| 351 | } |
| 352 | |
| 353 | uint64_t GetRand(uint64_t nMax) |
| 354 | { |
no test coverage detected