SecureRandom.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. using System;
  3. using System.Threading;
  4. using Org.BouncyCastle.Crypto;
  5. using Org.BouncyCastle.Crypto.Digests;
  6. using Org.BouncyCastle.Crypto.Prng;
  7. using Org.BouncyCastle.Utilities;
  8. namespace Org.BouncyCastle.Security
  9. {
  10. public class SecureRandom
  11. : Random
  12. {
  13. private static long counter = Times.NanoTime();
  14. #if NETCF_1_0 || PORTABLE
  15. private static object counterLock = new object();
  16. private static long NextCounterValue()
  17. {
  18. lock (counterLock)
  19. {
  20. return ++counter;
  21. }
  22. }
  23. private static readonly SecureRandom[] master = { null };
  24. private static SecureRandom Master
  25. {
  26. get
  27. {
  28. lock (master)
  29. {
  30. if (master[0] == null)
  31. {
  32. SecureRandom sr = master[0] = GetInstance("SHA256PRNG", false);
  33. // Even though Ticks has at most 8 or 14 bits of entropy, there's no harm in adding it.
  34. sr.SetSeed(DateTime.Now.Ticks);
  35. // 32 will be enough when ThreadedSeedGenerator is fixed. Until then, ThreadedSeedGenerator returns low
  36. // entropy, and this is not sufficient to be secure. http://www.bouncycastle.org/csharpdevmailarchive/msg00814.html
  37. sr.SetSeed(new ThreadedSeedGenerator().GenerateSeed(32, true));
  38. }
  39. return master[0];
  40. }
  41. }
  42. }
  43. #else
  44. private static long NextCounterValue()
  45. {
  46. return Interlocked.Increment(ref counter);
  47. }
  48. private static readonly SecureRandom master = new SecureRandom(new CryptoApiRandomGenerator());
  49. private static SecureRandom Master
  50. {
  51. get { return master; }
  52. }
  53. #endif
  54. private static DigestRandomGenerator CreatePrng(string digestName, bool autoSeed)
  55. {
  56. IDigest digest = DigestUtilities.GetDigest(digestName);
  57. if (digest == null)
  58. return null;
  59. DigestRandomGenerator prng = new DigestRandomGenerator(digest);
  60. if (autoSeed)
  61. {
  62. prng.AddSeedMaterial(NextCounterValue());
  63. prng.AddSeedMaterial(GetNextBytes(Master, digest.GetDigestSize()));
  64. }
  65. return prng;
  66. }
  67. public static byte[] GetNextBytes(SecureRandom secureRandom, int length)
  68. {
  69. byte[] result = new byte[length];
  70. secureRandom.NextBytes(result);
  71. return result;
  72. }
  73. /// <summary>
  74. /// Create and auto-seed an instance based on the given algorithm.
  75. /// </summary>
  76. /// <remarks>Equivalent to GetInstance(algorithm, true)</remarks>
  77. /// <param name="algorithm">e.g. "SHA256PRNG"</param>
  78. public static SecureRandom GetInstance(string algorithm)
  79. {
  80. return GetInstance(algorithm, true);
  81. }
  82. /// <summary>
  83. /// Create an instance based on the given algorithm, with optional auto-seeding
  84. /// </summary>
  85. /// <param name="algorithm">e.g. "SHA256PRNG"</param>
  86. /// <param name="autoSeed">If true, the instance will be auto-seeded.</param>
  87. public static SecureRandom GetInstance(string algorithm, bool autoSeed)
  88. {
  89. string upper = Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm);
  90. if (Org.BouncyCastle.Utilities.Platform.EndsWith(upper, "PRNG"))
  91. {
  92. string digestName = upper.Substring(0, upper.Length - "PRNG".Length);
  93. DigestRandomGenerator prng = CreatePrng(digestName, autoSeed);
  94. if (prng != null)
  95. {
  96. return new SecureRandom(prng);
  97. }
  98. }
  99. throw new ArgumentException("Unrecognised PRNG algorithm: " + algorithm, "algorithm");
  100. }
  101. [Obsolete("Call GenerateSeed() on a SecureRandom instance instead")]
  102. public static byte[] GetSeed(int length)
  103. {
  104. return GetNextBytes(Master, length);
  105. }
  106. protected readonly IRandomGenerator generator;
  107. public SecureRandom()
  108. : this(CreatePrng("SHA256", true))
  109. {
  110. }
  111. /// <remarks>
  112. /// To replicate existing predictable output, replace with GetInstance("SHA1PRNG", false), followed by SetSeed(seed)
  113. /// </remarks>
  114. [Obsolete("Use GetInstance/SetSeed instead")]
  115. public SecureRandom(byte[] seed)
  116. : this(CreatePrng("SHA1", false))
  117. {
  118. SetSeed(seed);
  119. }
  120. /// <summary>Use the specified instance of IRandomGenerator as random source.</summary>
  121. /// <remarks>
  122. /// This constructor performs no seeding of either the <c>IRandomGenerator</c> or the
  123. /// constructed <c>SecureRandom</c>. It is the responsibility of the client to provide
  124. /// proper seed material as necessary/appropriate for the given <c>IRandomGenerator</c>
  125. /// implementation.
  126. /// </remarks>
  127. /// <param name="generator">The source to generate all random bytes from.</param>
  128. public SecureRandom(IRandomGenerator generator)
  129. : base(0)
  130. {
  131. this.generator = generator;
  132. }
  133. public virtual byte[] GenerateSeed(int length)
  134. {
  135. return GetNextBytes(Master, length);
  136. }
  137. public virtual void SetSeed(byte[] seed)
  138. {
  139. generator.AddSeedMaterial(seed);
  140. }
  141. public virtual void SetSeed(long seed)
  142. {
  143. generator.AddSeedMaterial(seed);
  144. }
  145. public override int Next()
  146. {
  147. return NextInt() & int.MaxValue;
  148. }
  149. public override int Next(int maxValue)
  150. {
  151. if (maxValue < 2)
  152. {
  153. if (maxValue < 0)
  154. throw new ArgumentOutOfRangeException("maxValue", "cannot be negative");
  155. return 0;
  156. }
  157. int bits;
  158. // Test whether maxValue is a power of 2
  159. if ((maxValue & (maxValue - 1)) == 0)
  160. {
  161. bits = NextInt() & int.MaxValue;
  162. return (int)(((long)bits * maxValue) >> 31);
  163. }
  164. int result;
  165. do
  166. {
  167. bits = NextInt() & int.MaxValue;
  168. result = bits % maxValue;
  169. }
  170. while (bits - result + (maxValue - 1) < 0); // Ignore results near overflow
  171. return result;
  172. }
  173. public override int Next(int minValue, int maxValue)
  174. {
  175. if (maxValue <= minValue)
  176. {
  177. if (maxValue == minValue)
  178. return minValue;
  179. throw new ArgumentException("maxValue cannot be less than minValue");
  180. }
  181. int diff = maxValue - minValue;
  182. if (diff > 0)
  183. return minValue + Next(diff);
  184. for (;;)
  185. {
  186. int i = NextInt();
  187. if (i >= minValue && i < maxValue)
  188. return i;
  189. }
  190. }
  191. public override void NextBytes(byte[] buf)
  192. {
  193. generator.NextBytes(buf);
  194. }
  195. public virtual void NextBytes(byte[] buf, int off, int len)
  196. {
  197. generator.NextBytes(buf, off, len);
  198. }
  199. private static readonly double DoubleScale = System.Math.Pow(2.0, 64.0);
  200. public override double NextDouble()
  201. {
  202. return Convert.ToDouble((ulong) NextLong()) / DoubleScale;
  203. }
  204. public virtual int NextInt()
  205. {
  206. byte[] bytes = new byte[4];
  207. NextBytes(bytes);
  208. uint result = bytes[0];
  209. result <<= 8;
  210. result |= bytes[1];
  211. result <<= 8;
  212. result |= bytes[2];
  213. result <<= 8;
  214. result |= bytes[3];
  215. return (int)result;
  216. }
  217. public virtual long NextLong()
  218. {
  219. return ((long)(uint) NextInt() << 32) | (long)(uint) NextInt();
  220. }
  221. }
  222. }
  223. #endif