File: InsecureRandomDataProvider.cc

package info (click to toggle)
qpdf 12.3.0-1
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 72,644 kB
  • sloc: cpp: 59,031; perl: 12,172; ansic: 6,809; sh: 1,231; python: 1,041; xml: 43; makefile: 42
file content (42 lines) | stat: -rw-r--r-- 1,024 bytes parent folder | download
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
#include <qpdf/InsecureRandomDataProvider.hh>

#include <qpdf/QUtil.hh>
#include <qpdf/qpdf-config.h>
#include <cstdlib>

void
InsecureRandomDataProvider::provideRandomData(unsigned char* data, size_t len)
{
    for (size_t i = 0; i < len; ++i) {
        data[i] = static_cast<unsigned char>((this->random() & 0xff0) >> 4);
    }
}

long
InsecureRandomDataProvider::random()
{
    if (!this->seeded_random) {
        // Seed the random number generator with something simple, but just to be interesting, don't
        // use the unmodified current time.  It would be better if this were a more secure seed.
        auto seed = static_cast<unsigned int>(QUtil::get_current_time() ^ 0xcccc);
#ifdef HAVE_RANDOM
        ::srandom(seed);
#else
        srand(seed);
#endif
        this->seeded_random = true;
    }

#ifdef HAVE_RANDOM
    return ::random();
#else
    return rand();
#endif
}

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