Crypto++  5.6.3
Free C++ class library of cryptographic schemes
mersenne.h
Go to the documentation of this file.
1 // mersenne.h - written and placed in public domain by Jeffrey Walton.
2 // Copyright assigned to Crypto++ project.
3 
4 //! \file
5 //! \brief Class file for Mersenne Twister
6 //! \note Suitable for Monte Carlo simulations, and not cryptographic use
7 
8 #ifndef CRYPTOPP_MERSENNE_TWISTER_H
9 #define CRYPTOPP_MERSENNE_TWISTER_H
10 
11 #include "cryptlib.h"
12 #include "secblock.h"
13 #include "misc.h"
14 
15 NAMESPACE_BEGIN(CryptoPP)
16 
17 //! \class MersenneTwister
18 //! \brief Mersenne Twister class for Monte-Carlo simulations
19 //! \tparam K Magic constant
20 //! \tparam M Period parameter
21 //! \tparam N Size of the state vector
22 //! \tparam F Multiplier constant
23 //! \tparam S Sefault seed
24 //! \details Provides the MersenneTwister implementation. The class is a header-only implementation.
25 //! \warning MersenneTwister is suitable for simulations, where uniformaly distrubuted numbers are
26 //! required quickly. It should not be used for cryptographic purposes.
27 template <unsigned int K, unsigned int M, unsigned int N, unsigned int F, unsigned long S>
29 {
30 public:
31  //! \brief Construct a Mersenne Twister
32  //! \param seed 32-bit seed
33  //! \details Defaults to template parameter S due to changing algorithm
34  //! parameters over time
35  MersenneTwister(unsigned long seed = S) : m_seed(seed), m_idx(N)
36  {
37  m_state[0] = seed;
38  for (unsigned int i = 1; i < N+1; i++)
39  m_state[i] = word32(F * (m_state[i-1] ^ (m_state[i-1] >> 30)) + i);
40  }
41 
42  //! \brief Generate random array of bytes
43  //! \param output byte buffer
44  //! \param size length of the buffer, in bytes
45  //! \details Bytes are written to output in big endian order. If output length
46  //! is not a multiple of word32, then unused bytes are not accumulated for subsequent
47  //! calls to GenerateBlock. Rather, the unused tail bytes are discarded, and the
48  //! stream is continued at the next word32 boundary from the state array.
49  void GenerateBlock(byte *output, size_t size)
50  {
51  // Handle word32 size blocks
52  word32 temp;
53  for (size_t i=0; i < size/4; i++, output += 4)
54  {
55 #if defined(CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS) && defined(IS_LITTLE_ENDIAN)
56  *((word32*)output) = ByteReverse(NextMersenneWord());
57 #elif defined(CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS)
58  *((word32*)output) = NextMersenneWord();
59 #else
60  temp = NextMersenneWord();
61  output[3] = CRYPTOPP_GET_BYTE_AS_BYTE(temp, 0);
62  output[2] = CRYPTOPP_GET_BYTE_AS_BYTE(temp, 1);
63  output[1] = CRYPTOPP_GET_BYTE_AS_BYTE(temp, 2);
64  output[0] = CRYPTOPP_GET_BYTE_AS_BYTE(temp, 3);
65 #endif
66  }
67 
68  // No tail bytes
69  if (size%4 == 0)
70  {
71  // Wipe temp
72  *((volatile word32*)&temp) = 0;
73  return;
74  }
75 
76  // Handle tail bytes
77  temp = NextMersenneWord();
78  switch (size%4)
79  {
80  case 3: output[2] = CRYPTOPP_GET_BYTE_AS_BYTE(temp, 1); /* fall through */
81  case 2: output[1] = CRYPTOPP_GET_BYTE_AS_BYTE(temp, 2); /* fall through */
82  case 1: output[0] = CRYPTOPP_GET_BYTE_AS_BYTE(temp, 3); break;
83 
84  default: assert(0); ;;
85  }
86 
87  // Wipe temp
88  *((volatile word32*)&temp) = 0;
89  }
90 
91  //! \brief Generate a random 32-bit word in the range min to max, inclusive
92  //! \returns random 32-bit word in the range min to max, inclusive
93  //! \details If the 32-bit candidate is not within the range, then it is discarded
94  //! and a new candidate is used.
95  word32 GenerateWord32(word32 min=0, word32 max=0xffffffffL)
96  {
97  const word32 range = max-min;
98  if (range == 0xffffffffL)
99  return NextMersenneWord();
100 
101  const int maxBits = BitPrecision(range);
102  word32 value;
103 
104  do{
105  value = Crop(NextMersenneWord(), maxBits);
106  } while (value > range);
107 
108  return value+min;
109  }
110 
111  //! \brief Generate and discard n bytes
112  //! \param n the number of bytes to discard, rounded up to a <tt>word32</tt> size
113  //! \details If n is not a multiple of <tt>word32</tt>, then unused bytes are
114  //! not accumulated for subsequent calls to GenerateBlock. Rather, the unused
115  //! tail bytes are discarded, and the stream is continued at the next
116  //! <tt>word32</tt> boundary from the state array.
117  void DiscardBytes(size_t n)
118  {
119  for(size_t i=0; i < RoundUpToMultipleOf(n, 4U); i++)
120  NextMersenneWord();
121  }
122 
123 protected:
124 
125  //! \brief Returns the next 32-bit word from the state array
126  //! \returns the next 32-bit word from the state array
127  //! \details fetches the next word frm the state array, performs bit operations on
128  //! it, and then returns the value to the caller.
129  word32 NextMersenneWord()
130  {
131  if (m_idx >= N) { Twist(); }
132 
133  word32 temp = m_state[m_idx++];
134 
135  temp ^= (temp >> 11);
136  temp ^= (temp << 7) & 0x9D2C5680; // 0x9D2C5680 (2636928640)
137  temp ^= (temp << 15) & 0xEFC60000; // 0xEFC60000 (4022730752)
138 
139  return temp ^ (temp >> 18);
140  }
141 
142  //! \brief Performs the twist operaton on the state array
143  void Twist()
144  {
145  static const unsigned long magic[2]={0x0UL, K};
146  word32 kk, temp;
147 
148  assert(N >= M);
149  for (kk=0;kk<N-M;kk++)
150  {
151  temp = (m_state[kk] & 0x80000000)|(m_state[kk+1] & 0x7FFFFFFF);
152  m_state[kk] = m_state[kk+M] ^ (temp >> 1) ^ magic[temp & 0x1UL];
153  }
154 
155  for (;kk<N-1;kk++)
156  {
157  temp = (m_state[kk] & 0x80000000)|(m_state[kk+1] & 0x7FFFFFFF);
158  m_state[kk] = m_state[kk+(M-N)] ^ (temp >> 1) ^ magic[temp & 0x1UL];
159  }
160 
161  temp = (m_state[N-1] & 0x80000000)|(m_state[0] & 0x7FFFFFFF);
162  m_state[N-1] = m_state[M-1] ^ (temp >> 1) ^ magic[temp & 0x1UL];
163 
164  // Reset index
165  m_idx = 0;
166 
167  // Wipe temp
168  *((volatile word32*)&temp) = 0;
169  }
170 
171 private:
172 
173  //! \brief 32-bit word state array of size N
175  //! \brief the value used to seed the generator
176  unsigned int m_seed;
177  //! \brief the current index into the state array
178  unsigned int m_idx;
179 };
180 
181 //! \brief Original MT19937 generator provided in the ACM paper.
182 //! \details Also see http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/ARTICLES/mt.pdf; uses 4537 as default initial seed.
183 typedef MersenneTwister<0x9908B0DF /*2567483615*/, 397, 624, 0x10DCD /*69069*/, 4537> MT19937;
184 
185 //! \brief Updated MT19937 generator adapted to provide an array for initialization.
186 //! \details Also see http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html; uses 5489 as default initial seed.
187 //! \note Use this generator when interoperating with C++11's mt19937 class.
188 typedef MersenneTwister<0x9908B0DF /*2567483615*/, 397, 624, 0x6C078965 /*1812433253*/, 5489> MT19937ar;
189 
190 NAMESPACE_END
191 
192 #endif // CRYPTOPP_MERSENNE_TWISTER_H
193 
Utility functions for the Crypto++ library.
MersenneTwister< 0x9908B0DF, 397, 624, 0x10DCD, 4537 > MT19937
Original MT19937 generator provided in the ACM paper.
Definition: mersenne.h:183
Mersenne Twister class for Monte-Carlo simulations.
Definition: mersenne.h:28
Abstract base classes that provide a uniform interface to this library.
Interface for random number generators.
Definition: cryptlib.h:1085
Classes and functions for secure memory allocations.
T Crop(T value, size_t bits)
Truncates the value to the specified number of bits.
Definition: misc.h:647
void DiscardBytes(size_t n)
Generate and discard n bytes.
Definition: mersenne.h:117
void GenerateBlock(byte *output, size_t size)
Generate random array of bytes.
Definition: mersenne.h:49
MersenneTwister< 0x9908B0DF, 397, 624, 0x6C078965, 5489 > MT19937ar
Updated MT19937 generator adapted to provide an array for initialization.
Definition: mersenne.h:188
T1 RoundUpToMultipleOf(const T1 &n, const T2 &m)
Rounds a value up to a multiple of a second value.
Definition: misc.h:768
Crypto++ library namespace.
word32 GenerateWord32(word32 min=0, word32 max=0xffffffffL)
Generate a random 32-bit word in the range min to max, inclusive.
Definition: mersenne.h:95
byte ByteReverse(byte value)
Reverses bytes in a 8-bit value.
Definition: misc.h:1560
unsigned int BitPrecision(const T &value)
Returns the number of bits required for a value.
Definition: misc.h:574
MersenneTwister(unsigned long seed=S)
Construct a Mersenne Twister.
Definition: mersenne.h:35