random.cpp
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
22 #include "common.hpp"
23 
24 #include "random.hpp"
25 #include "../security/detail/openssl.hpp"
26 
27 #include <boost/nondet_random.hpp>
28 #include <boost/random/mersenne_twister.hpp>
29 #include <boost/random/uniform_int_distribution.hpp>
30 
31 namespace ndn {
32 namespace random {
33 
34 // OpenSSL-based (secure) pseudo-randomness generators
35 
36 uint32_t
38 {
39  uint32_t random;
40  generateSecureBytes(reinterpret_cast<uint8_t*>(&random), sizeof(random));
41  return random;
42 }
43 
44 uint64_t
46 {
47  uint64_t random;
48  generateSecureBytes(reinterpret_cast<uint8_t*>(&random), sizeof(random));
49  return random;
50 }
51 
52 void
53 generateSecureBytes(uint8_t* bytes, size_t size)
54 {
55  if (RAND_bytes(bytes, size) != 1) {
56  BOOST_THROW_EXCEPTION(std::runtime_error("Failed to generate random bytes (error code " +
57  std::to_string(ERR_get_error()) + ")"));
58  }
59 }
60 
61 // Boost.Random-based (simple) random generators
62 
63 static boost::random::mt19937&
65 {
66  static boost::random_device randomSeedGenerator;
67  static boost::random::mt19937 gen(randomSeedGenerator);
68 
69  return gen;
70 }
71 
72 uint32_t
74 {
75  static boost::random::uniform_int_distribution<uint32_t> distribution;
76  return distribution(getRandomGenerator());
77 }
78 
79 uint64_t
81 {
82  static boost::random::uniform_int_distribution<uint64_t> distribution;
83  return distribution(getRandomGenerator());
84 }
85 
86 
87 } // namespace random
88 } // namespace ndn
Copyright (c) 2013-2016 Regents of the University of California.
Definition: common.hpp:74
uint64_t generateSecureWord64()
Generate a cryptographically secure random integer from the range [0, 2^64)
Definition: random.cpp:45
uint32_t generateWord32()
Generate a cryptographically non-secure random integer from the range [0, 2^32)
Definition: random.cpp:73
uint32_t generateSecureWord32()
Generate a cryptographically secure random integer from the range [0, 2^32)
Definition: random.cpp:37
static boost::random::mt19937 & getRandomGenerator()
Definition: random.cpp:64
uint64_t generateWord64()
Generate a cryptographically non-secure random integer from range [0, 2^64)
Definition: random.cpp:80
void generateSecureBytes(uint8_t *bytes, size_t size)
Fill bytes of size with cryptographically secure random bytes.
Definition: random.cpp:53
std::string to_string(const V &v)
Definition: backports.hpp:51