Random: add getRandom(), returning std::vector<char>

このコミットが含まれているのは:
Albert S. 2021-03-26 22:44:08 +01:00
コミット 9840dbbeff
2個のファイルの変更24行の追加14行の削除

ファイルの表示

@ -21,6 +21,7 @@ SOFTWARE.
#include <sstream>
#include <exception>
#include <memory>
#include <vector>
#include "random.h"
#include "logger.h"
@ -28,25 +29,33 @@ Random::Random()
{
}
std::vector<char> Random::getRandom(unsigned int bytes)
{
auto buffer = std::make_unique<char[]>(bytes);
int r = getrandom(buffer.get(), bytes, GRND_NONBLOCK);
if(r != -1 && (size_t)r == bytes)
{
char *ptr = buffer.get();
return { ptr, ptr + bytes };
}
else
{
Logger::error() << "Random generator failed to get bytes: " + std::to_string(r);
throw std::runtime_error("Random generator failed");
}
}
std::string Random::getRandomHexString(unsigned int bytes)
{
std::stringstream stream;
auto buffer = std::make_unique<char[]>(bytes);
int r = getrandom(buffer.get(), bytes, GRND_NONBLOCK);
if(r != -1 && (size_t)r == bytes)
std::vector<char> random = getRandom(bytes);
for(size_t i = 0; i < random.size(); i++)
{
for(size_t i = 0; i < bytes; i++)
{
unsigned char c = (unsigned char)buffer[i];
stream << std::hex << (unsigned int)c;
}
return stream.str();
unsigned char c = (unsigned char)random[i];
stream << std::hex << (unsigned int)c;
}
else
{
return stream.str();
Logger::error() << "Random generator failed to get bytes: " + std::to_string(r);
throw std::runtime_error("Random generator failed");
}
}

ファイルの表示

@ -23,6 +23,7 @@ class Random
public:
Random();
std::string getRandomHexString(unsigned int bytes);
std::vector<char> getRandom(unsigned int bytes);
};
#endif // RANDOM_H