2015-09-06 20:33:27 +02:00
|
|
|
#include "./opensslrandomdevice.h"
|
|
|
|
|
|
|
|
#include "../io/cryptoexception.h"
|
2015-04-22 19:06:29 +02:00
|
|
|
|
|
|
|
#include <c++utilities/conversion/binaryconversion.h>
|
|
|
|
|
|
|
|
#include <openssl/err.h>
|
2017-05-01 03:25:30 +02:00
|
|
|
#include <openssl/rand.h>
|
2015-04-22 19:06:29 +02:00
|
|
|
|
|
|
|
#include <string>
|
|
|
|
|
|
|
|
using namespace std;
|
2019-06-10 22:44:29 +02:00
|
|
|
using namespace CppUtilities;
|
2015-04-22 19:06:29 +02:00
|
|
|
|
|
|
|
namespace Util {
|
|
|
|
|
|
|
|
/*!
|
|
|
|
* \class OpenSslRandomDevice
|
|
|
|
* \brief Provides a random device using the OpenSSL function RAND_bytes().
|
|
|
|
*/
|
|
|
|
|
|
|
|
/*!
|
|
|
|
* \brief Constructs a new random device.
|
|
|
|
*/
|
|
|
|
OpenSslRandomDevice::OpenSslRandomDevice()
|
2017-05-01 03:25:30 +02:00
|
|
|
{
|
|
|
|
}
|
2015-04-22 19:06:29 +02:00
|
|
|
|
|
|
|
/*!
|
|
|
|
* \brief Generates a new random number.
|
|
|
|
*/
|
2018-12-18 23:17:19 +01:00
|
|
|
OpenSslRandomDevice::result_type OpenSslRandomDevice::operator()() const
|
2017-05-01 03:25:30 +02:00
|
|
|
{
|
2015-04-22 19:06:29 +02:00
|
|
|
unsigned char buf[4];
|
2017-05-01 03:25:30 +02:00
|
|
|
if (RAND_bytes(buf, sizeof(buf))) {
|
2019-06-10 22:44:29 +02:00
|
|
|
return LE::toUInt32(reinterpret_cast<char *>(buf));
|
2018-06-09 19:47:50 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// handle error case
|
|
|
|
string errorMsg;
|
|
|
|
while (unsigned long errorCode = ERR_get_error()) {
|
|
|
|
if (!errorMsg.empty()) {
|
|
|
|
errorMsg += '\n';
|
2015-04-22 19:06:29 +02:00
|
|
|
}
|
2018-06-09 19:47:50 +02:00
|
|
|
errorMsg += ERR_error_string(errorCode, nullptr);
|
|
|
|
errorCode = ERR_get_error();
|
2015-04-22 19:06:29 +02:00
|
|
|
}
|
2018-12-21 17:31:24 +01:00
|
|
|
throw Io::CryptoException(move(errorMsg));
|
2015-04-22 19:06:29 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/*!
|
|
|
|
* \brief Returns the status.
|
|
|
|
*/
|
|
|
|
bool OpenSslRandomDevice::status() const
|
|
|
|
{
|
|
|
|
return RAND_status();
|
|
|
|
}
|
2018-03-20 20:11:31 +01:00
|
|
|
} // namespace Util
|