Random: add getRandom(), returning std::vector<char>
This commit is contained in:
bovenliggende
d507c507e4
commit
9840dbbeff
29
random.cpp
29
random.cpp
@ -21,6 +21,7 @@ SOFTWARE.
|
|||||||
#include <sstream>
|
#include <sstream>
|
||||||
#include <exception>
|
#include <exception>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
|
#include <vector>
|
||||||
#include "random.h"
|
#include "random.h"
|
||||||
#include "logger.h"
|
#include "logger.h"
|
||||||
|
|
||||||
@ -28,25 +29,33 @@ Random::Random()
|
|||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string Random::getRandomHexString(unsigned int bytes)
|
std::vector<char> Random::getRandom(unsigned int bytes)
|
||||||
{
|
{
|
||||||
std::stringstream stream;
|
|
||||||
|
|
||||||
auto buffer = std::make_unique<char[]>(bytes);
|
auto buffer = std::make_unique<char[]>(bytes);
|
||||||
int r = getrandom(buffer.get(), bytes, GRND_NONBLOCK);
|
int r = getrandom(buffer.get(), bytes, GRND_NONBLOCK);
|
||||||
if(r != -1 && (size_t)r == bytes)
|
if(r != -1 && (size_t)r == bytes)
|
||||||
{
|
{
|
||||||
for(size_t i = 0; i < bytes; i++)
|
char *ptr = buffer.get();
|
||||||
{
|
return { ptr, ptr + bytes };
|
||||||
unsigned char c = (unsigned char)buffer[i];
|
|
||||||
stream << std::hex << (unsigned int)c;
|
|
||||||
}
|
|
||||||
return stream.str();
|
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
|
|
||||||
Logger::error() << "Random generator failed to get bytes: " + std::to_string(r);
|
Logger::error() << "Random generator failed to get bytes: " + std::to_string(r);
|
||||||
throw std::runtime_error("Random generator failed");
|
throw std::runtime_error("Random generator failed");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string Random::getRandomHexString(unsigned int bytes)
|
||||||
|
{
|
||||||
|
std::stringstream stream;
|
||||||
|
|
||||||
|
std::vector<char> random = getRandom(bytes);
|
||||||
|
for(size_t i = 0; i < random.size(); i++)
|
||||||
|
{
|
||||||
|
unsigned char c = (unsigned char)random[i];
|
||||||
|
stream << std::hex << (unsigned int)c;
|
||||||
|
}
|
||||||
|
return stream.str();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
1
random.h
1
random.h
@ -23,6 +23,7 @@ class Random
|
|||||||
public:
|
public:
|
||||||
Random();
|
Random();
|
||||||
std::string getRandomHexString(unsigned int bytes);
|
std::string getRandomHexString(unsigned int bytes);
|
||||||
|
std::vector<char> getRandom(unsigned int bytes);
|
||||||
};
|
};
|
||||||
|
|
||||||
#endif // RANDOM_H
|
#endif // RANDOM_H
|
||||||
|
Laden…
Verwijs in nieuw issue
Block a user