mersenne.h 7.6 KB

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