passwordfile/util/opensslrandomdevice.cpp

58 lines
1.2 KiB
C++
Raw Normal View History

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;
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.
*/
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))) {
2015-04-22 19:06:29 +02:00
return ConversionUtilities::LE::toUInt32(reinterpret_cast<char *>(buf));
}
// 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
}
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