Common: Add Random utilities

This makes it easier to generate random numbers or fill a buffer with
random data in a cryptographically secure way.

This also replaces existing usages of RNG functions in the codebase:

* <random> is pretty hard to use correctly, and std::random_device does
  not give enough guarantees about its results (it's
  implementation-defined, non cryptographically secure and could be
  deterministic on some platforms).
  Doing things correctly is error prone and verbose.

* rand() is terrible and should not be used especially in crypto code.
This commit is contained in:
Léo Lam
2018-05-21 15:48:17 +02:00
parent dd77ace56a
commit fff1db9730
10 changed files with 91 additions and 71 deletions

View File

@@ -4,7 +4,6 @@
#include <mbedtls/sha1.h>
#include <memory>
#include <mutex>
#include <random>
#include <string>
#if defined(_WIN32)
@@ -16,6 +15,7 @@
#include "Common/Analytics.h"
#include "Common/CPUDetect.h"
#include "Common/CommonTypes.h"
#include "Common/Random.h"
#include "Common/StringUtil.h"
#include "Common/Version.h"
#include "Core/ConfigManager.h"
@@ -73,9 +73,9 @@ void DolphinAnalytics::ReloadConfig()
void DolphinAnalytics::GenerateNewIdentity()
{
std::random_device rd;
u64 id_high = (static_cast<u64>(rd()) << 32) | rd();
u64 id_low = (static_cast<u64>(rd()) << 32) | rd();
u64 id_high, id_low;
Common::Random::Generate(&id_high, sizeof(id_high));
Common::Random::Generate(&id_low, sizeof(id_low));
m_unique_id = StringFromFormat("%016" PRIx64 "%016" PRIx64, id_high, id_low);
// Save the new id in the configuration.