passwordfile/util/opensslrandomdevice.cpp

63 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 {
/*!
* \namespace QtGui
* \brief Contains all miscellaneous utility functions.
*/
/*!
* \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.
*/
2017-05-01 03:25:30 +02:00
uint32 OpenSslRandomDevice::operator()() const
{
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));
} else {
string msg;
unsigned long errorCode = ERR_get_error();
2017-05-01 03:25:30 +02:00
while (errorCode != 0) {
if (!msg.empty()) {
msg += '\n';
2015-04-22 19:06:29 +02:00
}
msg += ERR_error_string(errorCode, 0);
errorCode = ERR_get_error();
}
throw Io::CryptoException(msg);
}
}
/*!
* \brief Returns the status.
*/
bool OpenSslRandomDevice::status() const
{
return RAND_status();
}
}