summaryrefslogtreecommitdiffstats
path: root/libqpdf/SecureRandomDataProvider.cc
blob: 14ef55a72706d78d798a686cd11f6b946d131c39 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <qpdf/SecureRandomDataProvider.hh>

#include <qpdf/qpdf-config.h>
#include <qpdf/QUtil.hh>
#ifdef _WIN32
# include <Windows.h>
# include <direct.h>
# include <io.h>
# ifndef SKIP_OS_SECURE_RANDOM
#  include <Wincrypt.h>
# endif
#endif

SecureRandomDataProvider::SecureRandomDataProvider()
{
}

SecureRandomDataProvider::~SecureRandomDataProvider()
{
}

#ifdef _WIN32

class WindowsCryptProvider
{
  public:
    WindowsCryptProvider()
    {
        if (! CryptAcquireContext(&crypt_prov, NULL, NULL, PROV_RSA_FULL, 0))
        {
            throw std::runtime_error("unable to acquire crypt context");
        }
    }
    ~WindowsCryptProvider()
    {
        // Ignore error
        CryptReleaseContext(crypt_prov, 0);
    }

    HCRYPTPROV crypt_prov;
};
#endif

void
SecureRandomDataProvider::provideRandomData(unsigned char* data, size_t len)
{
#if defined(_WIN32)

    // Optimization: make the WindowsCryptProvider static as long as
    // it can be done in a thread-safe fashion.
    WindowsCryptProvider c;
    if (! CryptGenRandom(c.crypt_prov, len, reinterpret_cast<BYTE*>(data)))
    {
        throw std::runtime_error("unable to generate secure random data");
    }

#elif defined(RANDOM_DEVICE)

    // Optimization: wrap the file open and close in a class so that
    // the file is closed in a destructor, then make this static to
    // keep the file handle open.  Only do this if it can be done in a
    // thread-safe fashion.
    FILE* f = QUtil::safe_fopen(RANDOM_DEVICE, "rb");
    size_t fr = fread(data, 1, len, f);
    fclose(f);
    if (fr != len)
    {
        throw std::runtime_error(
            "unable to read " +
            QUtil::int_to_string(len) +
            " bytes from " + std::string(RANDOM_DEVICE));
    }

#else

#  error "Don't know how to generate secure random numbers on this platform.  See random number generation in the top-level README"

#endif
}

RandomDataProvider*
SecureRandomDataProvider::getInstance()
{
    static SecureRandomDataProvider instance;
    return &instance;
}