util: generate random bytes using OpenSSL instead of CryptoPP

Change-Id: I68bdac565242432fa53a1f113d6f395bf3c6e982
Refs: #3010, #2949
diff --git a/src/security/detail/openssl.hpp b/src/security/detail/openssl.hpp
index 09a6f68..d3ab592 100644
--- a/src/security/detail/openssl.hpp
+++ b/src/security/detail/openssl.hpp
@@ -40,6 +40,6 @@
 #include <openssl/pem.h>
 #include <openssl/hmac.h>
 #include <openssl/x509.h>
-
+#include <openssl/err.h>
 
 #endif // NDN_SECURITY_DETAIL_OPENSSL_HPP
diff --git a/src/util/random.cpp b/src/util/random.cpp
index f321bbd..a16d587 100644
--- a/src/util/random.cpp
+++ b/src/util/random.cpp
@@ -1,6 +1,6 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
 /**
- * Copyright (c) 2013-2014 Regents of the University of California.
+ * Copyright (c) 2013-2016 Regents of the University of California.
  *
  * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
  *
@@ -22,42 +22,42 @@
 #include "common.hpp"
 
 #include "random.hpp"
+#include "../security/detail/openssl.hpp"
 
 #include <boost/nondet_random.hpp>
 #include <boost/random/mersenne_twister.hpp>
 #include <boost/random/uniform_int_distribution.hpp>
 
-#include "../security/cryptopp.hpp"
-
 namespace ndn {
 namespace random {
 
-// CryptoPP-based (secure) random generators
-
-static CryptoPP::AutoSeededRandomPool&
-getSecureRandomGenerator()
-{
-  static CryptoPP::AutoSeededRandomPool rng;
-
-  return rng;
-}
+// OpenSSL-based (secure) pseudo-randomness generators
 
 uint32_t
 generateSecureWord32()
 {
-  return getSecureRandomGenerator().GenerateWord32();
+  uint32_t random;
+  generateSecureBytes(reinterpret_cast<uint8_t*>(&random), sizeof(random));
+  return random;
 }
 
 uint64_t
 generateSecureWord64()
 {
   uint64_t random;
-  getSecureRandomGenerator()
-    .GenerateBlock(reinterpret_cast<unsigned char*>(&random), sizeof(uint64_t));
-
+  generateSecureBytes(reinterpret_cast<uint8_t*>(&random), sizeof(random));
   return random;
 }
 
+void
+generateSecureBytes(uint8_t* bytes, size_t size)
+{
+  if (RAND_bytes(bytes, size) != 1) {
+    BOOST_THROW_EXCEPTION(std::runtime_error("Failed to generate random bytes (error code " +
+                                             std::to_string(ERR_get_error()) + ")"));
+  }
+}
+
 // Boost.Random-based (simple) random generators
 
 static boost::random::mt19937&
diff --git a/src/util/random.hpp b/src/util/random.hpp
index 6dc1b52..e47b5fb 100644
--- a/src/util/random.hpp
+++ b/src/util/random.hpp
@@ -1,6 +1,6 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
 /**
- * Copyright (c) 2013-2014 Regents of the University of California.
+ * Copyright (c) 2013-2016 Regents of the University of California.
  *
  * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
  *
@@ -30,7 +30,7 @@
 /**
  * @brief Generate a cryptographically secure random integer from the range [0, 2^32)
  *
- * This method uses CryptoPP routines
+ * @throw std::runtime_error if generation fails.
  */
 uint32_t
 generateSecureWord32();
@@ -38,12 +38,20 @@
 /**
  * @brief Generate a cryptographically secure random integer from the range [0, 2^64)
  *
- * This method uses CryptoPP routines
+ * @throw std::runtime_error if generation fails.
  */
 uint64_t
 generateSecureWord64();
 
 /**
+ * @brief Fill @p bytes of @p size with cryptographically secure random bytes
+ *
+ * @throw std::runtime_error if generation fails.
+ */
+void
+generateSecureBytes(uint8_t* bytes, size_t size);
+
+/**
  * @brief Generate a cryptographically non-secure random integer from the range [0, 2^32)
  *
  * This method uses Boost.Random routines
diff --git a/tests/unit-tests/util/random.t.cpp b/tests/unit-tests/util/random.t.cpp
index d56d84b..18af4ff 100644
--- a/tests/unit-tests/util/random.t.cpp
+++ b/tests/unit-tests/util/random.t.cpp
@@ -1,6 +1,6 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
 /**
- * Copyright (c) 2013-2015 Regents of the University of California.
+ * Copyright (c) 2013-2016 Regents of the University of California.
  *
  * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
  *
@@ -23,13 +23,15 @@
 
 #include "boost-test.hpp"
 #include <boost/mpl/vector.hpp>
+#include "security/detail/openssl.hpp"
 
 #include <cmath>
 
 namespace ndn {
 namespace tests {
 
-BOOST_AUTO_TEST_SUITE(UtilRandom)
+BOOST_AUTO_TEST_SUITE(Util)
+BOOST_AUTO_TEST_SUITE(TestRandom)
 
 class PseudoRandomWord32
 {
@@ -76,11 +78,31 @@
                            SecureRandomWord32,
                            SecureRandomWord64> RandomGenerators;
 
-BOOST_AUTO_TEST_CASE_TEMPLATE(GoodnessOfFit, RandomGenerator, RandomGenerators)
+
+static double
+getDeviation(const std::vector<uint32_t>& counts, size_t size)
 {
   // Kolmogorov-Smirnov Goodness-of-Fit Test
   // http://www.itl.nist.gov/div898/handbook/eda/section3/eda35g.htm
 
+  std::vector<double> edf(counts.size(), 0.0);
+  double probability = 0.0;
+  for (size_t i = 0; i < counts.size(); i++) {
+    probability += 1.0 * counts[i] / size;
+    edf[i] = probability;
+  }
+
+  double t = 0.0;
+  for (size_t i = 0; i < counts.size(); i++) {
+    t = std::max(t, std::abs(edf[i] - (i * 1.0 / counts.size())));
+  }
+
+  return t;
+}
+
+
+BOOST_AUTO_TEST_CASE_TEMPLATE(GoodnessOfFit, RandomGenerator, RandomGenerators)
+{
   const size_t MAX_BINS = 32;
   const uint32_t MAX_ITERATIONS = 35;
 
@@ -90,24 +112,98 @@
     counts[RandomGenerator::generate() % MAX_BINS]++;
   }
 
-  std::vector<double> edf(MAX_BINS, 0.0);
-  double probability = 0.0;
-  for (size_t i = 0; i < MAX_BINS; i++) {
-    probability += 1.0 * counts[i] / MAX_ITERATIONS;
-    edf[i] = probability;
-  }
+  // Check if it is uniform distribution with confidence 0.95
+  // http://dlc.erieri.com/onlinetextbook/index.cfm?fuseaction=textbook.appendix&FileName=Table7
+  BOOST_WARN_LE(getDeviation(counts, MAX_ITERATIONS), 0.230);
+}
 
-  double t = 0.0;
-  for (size_t i = 0; i < MAX_BINS; i++) {
-    t = std::max(t, std::abs(edf[i] - (i * 1.0 / MAX_BINS)));
+BOOST_AUTO_TEST_CASE(GenerateRandomBytes)
+{
+  // Kolmogorov-Smirnov Goodness-of-Fit Test
+  // http://www.itl.nist.gov/div898/handbook/eda/section3/eda35g.htm
+
+  uint8_t buf[1024] = {0};
+  random::generateSecureBytes(buf, sizeof(buf));
+
+  std::vector<uint32_t> counts(256, 0);
+
+  for (size_t i = 0; i < sizeof(buf); i++) {
+    counts[buf[i]]++;
   }
 
   // Check if it is uniform distribution with confidence 0.95
   // http://dlc.erieri.com/onlinetextbook/index.cfm?fuseaction=textbook.appendix&FileName=Table7
-  BOOST_WARN_LE(t, 0.230);
+  BOOST_WARN_LE(getDeviation(counts, sizeof(buf)), 0.230);
 }
 
-BOOST_AUTO_TEST_SUITE_END()
+// This fixture uses OpenSSL routines to set a dummy random generator that always fails
+class FailRandMethodFixture
+{
+public:
+  FailRandMethodFixture()
+    : m_dummyRandMethod{&FailRandMethodFixture::seed,
+                        &FailRandMethodFixture::bytes,
+                        &FailRandMethodFixture::cleanup,
+                        &FailRandMethodFixture::add,
+                        &FailRandMethodFixture::pseudorand,
+                        &FailRandMethodFixture::status}
+  {
+    m_origRandMethod = RAND_get_rand_method();
+    RAND_set_rand_method(&m_dummyRandMethod);
+  }
+
+  ~FailRandMethodFixture()
+  {
+    RAND_set_rand_method(m_origRandMethod);
+  }
+
+private: // RAND_METHOD callbacks
+  static void
+  seed(const void* buf, int num)
+  {
+  }
+
+  static int
+  bytes(unsigned char *buf, int num)
+  {
+    return 0;
+  }
+
+  static void
+  cleanup()
+  {
+  }
+
+  static void
+  add(const void *buf, int num, double entropy)
+  {
+  }
+
+  static int
+  pseudorand(unsigned char *buf, int num)
+  {
+    return 0;
+  }
+
+  static int
+  status()
+  {
+    return 0;
+  }
+
+private:
+  const RAND_METHOD* m_origRandMethod;
+  RAND_METHOD m_dummyRandMethod;
+};
+
+BOOST_FIXTURE_TEST_CASE(Error, FailRandMethodFixture)
+{
+  uint8_t buf[1024] = {0};
+  BOOST_CHECK_THROW(random::generateSecureBytes(buf, sizeof(buf)), std::runtime_error);
+}
+
+BOOST_AUTO_TEST_SUITE_END() // TestRandom
+BOOST_AUTO_TEST_SUITE_END() // Util
 
 } // namespace tests
 } // namespace ndn