diff --git a/include/qpdf/QUtil.hh b/include/qpdf/QUtil.hh index cdeefd71..8baedab6 100644 --- a/include/qpdf/QUtil.hh +++ b/include/qpdf/QUtil.hh @@ -83,6 +83,18 @@ namespace QUtil // encoding for the unicode value passed in. QPDF_DLL std::string toUTF8(unsigned long uval); + + // Wrapper around random from stdlib. Calls srandom automatically + // the first time it is called. + QPDF_DLL + long random(); + + // Wrapper around srandom from stdlib. + QPDF_DLL + void srandom(unsigned int seed); + + QPDF_DLL + void initializeWithRandomBytes(unsigned char* data, size_t len); }; #endif // __QUTIL_HH__ diff --git a/libqpdf/Pl_AES_PDF.cc b/libqpdf/Pl_AES_PDF.cc index 09c975d6..52876101 100644 --- a/libqpdf/Pl_AES_PDF.cc +++ b/libqpdf/Pl_AES_PDF.cc @@ -6,11 +6,6 @@ #include #include #include -#include -#ifndef HAVE_RANDOM -# define random rand -# define srandom srand -#endif bool Pl_AES_PDF::use_static_iv = false; @@ -155,15 +150,6 @@ Pl_AES_PDF::finish() void Pl_AES_PDF::initializeVector() { - static bool seeded_random = false; - if (! seeded_random) - { - // Seed the random number generator with something simple, but - // just to be interesting, don't use the unmodified current - // time.... - srandom((int)QUtil::get_current_time() ^ 0xcccc); - seeded_random = true; - } if (use_zero_iv) { for (unsigned int i = 0; i < this->buf_size; ++i) @@ -184,10 +170,7 @@ Pl_AES_PDF::initializeVector() } else { - for (unsigned int i = 0; i < this->buf_size; ++i) - { - this->cbc_block[i] = (unsigned char)((random() & 0xff0) >> 4); - } + QUtil::initializeWithRandomBytes(this->cbc_block, this->buf_size); } } diff --git a/libqpdf/QUtil.cc b/libqpdf/QUtil.cc index 20143087..3cdfdc49 100644 --- a/libqpdf/QUtil.cc +++ b/libqpdf/QUtil.cc @@ -333,3 +333,42 @@ QUtil::toUTF8(unsigned long uval) return result; } + +long +QUtil::random() +{ + static bool seeded_random = false; + if (! seeded_random) + { + // Seed the random number generator with something simple, but + // just to be interesting, don't use the unmodified current + // time.... + QUtil::srandom((int)QUtil::get_current_time() ^ 0xcccc); + seeded_random = true; + } + +#ifdef HAVE_RANDOM + return ::random(); +#else + return rand(); +#endif +} + +void +QUtil::srandom(unsigned int seed) +{ +#ifdef HAVE_RANDOM + ::srandom(seed); +#else + srand(seed); +#endif +} + +void +QUtil::initializeWithRandomBytes(unsigned char* data, size_t len) +{ + for (size_t i = 0; i < len; ++i) + { + data[i] = (unsigned char)((QUtil::random() & 0xff0) >> 4); + } +}