passwordfile/util/opensslrandomdevice.cpp

59 lines
1.2 KiB
C++
Raw Permalink 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;
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.
*/
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));
}
// 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
}
2023-02-18 19:03:29 +01:00
throw Io::CryptoException(std::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