Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

192 lines
6.3 KiB

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