Add Visione backend foundation
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
#include "common/Crypto.h"
|
||||
|
||||
#include <drogon/utils/Utilities.h>
|
||||
|
||||
#include <iomanip>
|
||||
#include <random>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
|
||||
namespace visione::crypto
|
||||
{
|
||||
std::string sha256(const std::string &value)
|
||||
{
|
||||
return drogon::utils::getSha256(value);
|
||||
}
|
||||
|
||||
std::string randomNumericCode(int digits)
|
||||
{
|
||||
std::random_device device;
|
||||
std::mt19937 generator(device());
|
||||
std::uniform_int_distribution<int> distribution(0, 9);
|
||||
|
||||
std::string code;
|
||||
code.reserve(static_cast<size_t>(digits));
|
||||
for (int i = 0; i < digits; ++i)
|
||||
{
|
||||
code.push_back(static_cast<char>('0' + distribution(generator)));
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
std::string randomToken()
|
||||
{
|
||||
return drogon::utils::getUuid() + drogon::utils::getUuid();
|
||||
}
|
||||
|
||||
std::string hashPassword(const std::string &password)
|
||||
{
|
||||
const auto salt = drogon::utils::getUuid();
|
||||
return "sha256$" + salt + "$" + sha256(salt + ":" + password);
|
||||
}
|
||||
|
||||
bool verifyPassword(const std::string &password, const std::string &hash)
|
||||
{
|
||||
constexpr std::string_view prefix = "sha256$";
|
||||
if (!hash.starts_with(prefix))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto saltStart = prefix.size();
|
||||
const auto hashStart = hash.find('$', saltStart);
|
||||
if (hashStart == std::string::npos)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto salt = hash.substr(saltStart, hashStart - saltStart);
|
||||
const auto expected = "sha256$" + salt + "$" + sha256(salt + ":" + password);
|
||||
return expected == hash;
|
||||
}
|
||||
|
||||
std::string hashSecret(const std::string &secret)
|
||||
{
|
||||
return sha256("visione:" + secret);
|
||||
}
|
||||
} // namespace visione::crypto
|
||||
|
||||
Reference in New Issue
Block a user