diff --git a/Source/Core/Common/Random.h b/Source/Core/Common/Random.h index 430b24201c..1f234f8ac3 100644 --- a/Source/Core/Common/Random.h +++ b/Source/Core/Common/Random.h @@ -5,6 +5,7 @@ #pragma once #include +#include #include "Common/CommonTypes.h" @@ -12,4 +13,14 @@ namespace Common::Random { /// Fill `buffer` with random bytes using a cryptographically secure pseudo-random number generator. void Generate(void* buffer, std::size_t size); + +/// Generates a random value of arithmetic type `T` +template +T GenerateValue() +{ + static_assert(std::is_arithmetic(), "T must be an arithmetic type in GenerateValue."); + T value; + Generate(&value, sizeof(value)); + return value; +} } // namespace Common::Random diff --git a/Source/Core/Common/TraversalClient.cpp b/Source/Core/Common/TraversalClient.cpp index 36eb431c7f..34c16ddff4 100644 --- a/Source/Core/Common/TraversalClient.cpp +++ b/Source/Core/Common/TraversalClient.cpp @@ -270,7 +270,7 @@ TraversalRequestId TraversalClient::SendTraversalPacket(const TraversalPacket& p { OutgoingTraversalPacketInfo info; info.packet = packet; - Common::Random::Generate(&info.packet.requestId, sizeof(info.packet.requestId)); + info.packet.requestId = Common::Random::GenerateValue(); info.tries = 0; m_OutgoingTraversalPackets.push_back(info); ResendPacket(&m_OutgoingTraversalPackets.back()); diff --git a/Source/Core/Common/TraversalServer.cpp b/Source/Core/Common/TraversalServer.cpp index 097418b143..40c439f6b4 100644 --- a/Source/Core/Common/TraversalServer.cpp +++ b/Source/Core/Common/TraversalServer.cpp @@ -169,8 +169,7 @@ static sockaddr_in6 MakeSinAddr(const TraversalInetAddress& addr) static void GetRandomHostId(TraversalHostId* hostId) { char buf[9]; - u32 num; - Common::Random::Generate(&num, sizeof(num)); + const u32 num = Common::Random::GenerateValue(); sprintf(buf, "%08x", num); memcpy(hostId->data(), buf, 8); } diff --git a/Source/Core/Core/Analytics.cpp b/Source/Core/Core/Analytics.cpp index 9c0608ef59..e6fdc9309a 100644 --- a/Source/Core/Core/Analytics.cpp +++ b/Source/Core/Core/Analytics.cpp @@ -73,9 +73,8 @@ void DolphinAnalytics::ReloadConfig() void DolphinAnalytics::GenerateNewIdentity() { - u64 id_high, id_low; - Common::Random::Generate(&id_high, sizeof(id_high)); - Common::Random::Generate(&id_low, sizeof(id_low)); + const u64 id_high = Common::Random::GenerateValue(); + const u64 id_low = Common::Random::GenerateValue(); m_unique_id = StringFromFormat("%016" PRIx64 "%016" PRIx64, id_high, id_low); // Save the new id in the configuration.