From 5e3bad2f86665b35155095b91a2d672fc7335870 Mon Sep 17 00:00:00 2001 From: Jay Berkenbilt Date: Sat, 30 Nov 2013 12:02:56 -0500 Subject: Refactor random data generation Add new RandomDataProvider object and implement existing random number generation in terms of that. This enables end users to supply their own random data providers. --- libtests/build.mk | 1 + libtests/qtest/random.test | 16 ++++++++++++ libtests/random.cc | 65 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 82 insertions(+) create mode 100644 libtests/qtest/random.test create mode 100644 libtests/random.cc (limited to 'libtests') diff --git a/libtests/build.mk b/libtests/build.mk index 7a535953..22d9299e 100644 --- a/libtests/build.mk +++ b/libtests/build.mk @@ -12,6 +12,7 @@ BINS_libtests = \ png_filter \ pointer_holder \ qutil \ + random \ rc4 \ sha2 diff --git a/libtests/qtest/random.test b/libtests/qtest/random.test new file mode 100644 index 00000000..c3b4b9d7 --- /dev/null +++ b/libtests/qtest/random.test @@ -0,0 +1,16 @@ +#!/usr/bin/env perl +require 5.008; +BEGIN { $^W = 1; } +use strict; + +require TestDriver; + +my $td = new TestDriver('random'); + +$td->runtest("Random Data Providers", + {$td->COMMAND => "random"}, + {$td->STRING => "random: end of tests\n", + $td->EXIT_STATUS => 0}, + $td->NORMALIZE_NEWLINES); + +$td->report(1); diff --git a/libtests/random.cc b/libtests/random.cc new file mode 100644 index 00000000..644fdd91 --- /dev/null +++ b/libtests/random.cc @@ -0,0 +1,65 @@ +#include +#include +#include +#include + +class BogusRandomDataProvider: public RandomDataProvider +{ + public: + virtual ~BogusRandomDataProvider() + { + } + BogusRandomDataProvider() + { + } + virtual void provideRandomData(unsigned char* data, size_t len) + { + for (size_t i = 0; i < len; ++i) + { + data[i] = static_cast(i & 0xff); + } + } +}; + +int main() +{ + long r1 = QUtil::random(); + long r2 = QUtil::random(); + if (r1 == r2) + { + std::cout << "fail: two randoms were the same\n"; + } + InsecureRandomDataProvider irdp; + irdp.provideRandomData(reinterpret_cast(&r1), 4); + irdp.provideRandomData(reinterpret_cast(&r2), 4); + if (r1 == r2) + { + std::cout << "fail: two insecure randoms were the same\n"; + } + SecureRandomDataProvider srdp; + srdp.provideRandomData(reinterpret_cast(&r1), 4); + srdp.provideRandomData(reinterpret_cast(&r2), 4); + if (r1 == r2) + { + std::cout << "fail: two secure randoms were the same\n"; + } + BogusRandomDataProvider brdp; + QUtil::setRandomDataProvider(&brdp); + r1 = QUtil::random(); + r2 = QUtil::random(); + if (r1 != r2) + { + std::cout << "fail: two bogus randoms were different\n"; + } + unsigned char buf[4]; + QUtil::initializeWithRandomBytes(buf, 4); + if (! ((buf[0] == 0) && + (buf[1] == 1) && + (buf[2] == 2) && + (buf[3] == 3))) + { + std::cout << "fail: bogus random didn't provide correct bytes\n"; + } + std::cout << "random: end of tests\n"; + return 0; +} -- cgit v1.2.3-54-g00ecf