From 3903ac6526e05088f2b9409990c058e2152b367b Mon Sep 17 00:00:00 2001 From: David Cernat Date: Sat, 21 Sep 2019 14:22:19 +0300 Subject: [PATCH] [Server] Add script functions for getting SHA256 hashes & random strings --- .../Script/Functions/Miscellaneous.cpp | 29 +++++++++++++++++++ .../Script/Functions/Miscellaneous.hpp | 21 ++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/apps/openmw-mp/Script/Functions/Miscellaneous.cpp b/apps/openmw-mp/Script/Functions/Miscellaneous.cpp index e81bc73c8..af6bed420 100644 --- a/apps/openmw-mp/Script/Functions/Miscellaneous.cpp +++ b/apps/openmw-mp/Script/Functions/Miscellaneous.cpp @@ -4,9 +4,38 @@ #include +#include + #include +#include + using namespace std; +const char *MiscellaneousFunctions::GenerateRandomString(unsigned int length) noexcept +{ + const std::string characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + + std::random_device randomDevice; + std::mt19937 generator(randomDevice()); + std::uniform_int_distribution<> distribution(0, characters.size() - 1); + + std::string randomString; + + for (std::size_t i = 0; i < length; ++i) + { + randomString += characters[distribution(generator)]; + } + + return randomString.c_str(); +} + +const char *MiscellaneousFunctions::GetSHA256Hash(const char* inputString) noexcept +{ + std::string hashString = picosha2::hash256_hex_string(std::string{inputString}); + + return hashString.c_str(); +} + unsigned int MiscellaneousFunctions::GetLastPlayerId() noexcept { return Players::getLastPlayerId(); diff --git a/apps/openmw-mp/Script/Functions/Miscellaneous.hpp b/apps/openmw-mp/Script/Functions/Miscellaneous.hpp index 96b646579..ae3bb843f 100644 --- a/apps/openmw-mp/Script/Functions/Miscellaneous.hpp +++ b/apps/openmw-mp/Script/Functions/Miscellaneous.hpp @@ -4,6 +4,10 @@ #include "../Types.hpp" #define MISCELLANEOUSAPI \ + {"GenerateRandomString", MiscellaneousFunctions::GenerateRandomString},\ + \ + {"GetSHA256Hash", MiscellaneousFunctions::GetSHA256Hash},\ + \ {"GetLastPlayerId", MiscellaneousFunctions::GetLastPlayerId},\ \ {"GetCurrentMpNum", MiscellaneousFunctions::GetCurrentMpNum},\ @@ -13,6 +17,23 @@ class MiscellaneousFunctions { public: + /** + * \brief Generate a random string of a particular length that only contains + * letters and numbers. + * + * \param length The length of the generated string. + * \return The generated string. + */ + static const char *GenerateRandomString(unsigned int length) noexcept; + + /** + * \brief Get the SHA256 hash corresponding to an input string. + * + * \param inputString The input string. + * \return The SHA256 hash. + */ + static const char *GetSHA256Hash(const char* inputString) noexcept; + /** * \brief Get the last player ID currently connected to the server. *