X931SecureRandom.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
  5. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng
  6. {
  7. public class X931SecureRandom
  8. : SecureRandom
  9. {
  10. private readonly bool mPredictionResistant;
  11. private readonly SecureRandom mRandomSource;
  12. private readonly X931Rng mDrbg;
  13. internal X931SecureRandom(SecureRandom randomSource, X931Rng drbg, bool predictionResistant)
  14. : base((IRandomGenerator)null)
  15. {
  16. this.mRandomSource = randomSource;
  17. this.mDrbg = drbg;
  18. this.mPredictionResistant = predictionResistant;
  19. }
  20. public override void SetSeed(byte[] seed)
  21. {
  22. lock (this)
  23. {
  24. if (mRandomSource != null)
  25. {
  26. this.mRandomSource.SetSeed(seed);
  27. }
  28. }
  29. }
  30. public override void SetSeed(long seed)
  31. {
  32. lock (this)
  33. {
  34. // this will happen when SecureRandom() is created
  35. if (mRandomSource != null)
  36. {
  37. this.mRandomSource.SetSeed(seed);
  38. }
  39. }
  40. }
  41. public override void NextBytes(byte[] bytes)
  42. {
  43. lock (this)
  44. {
  45. // check if a reseed is required...
  46. if (mDrbg.Generate(bytes, mPredictionResistant) < 0)
  47. {
  48. mDrbg.Reseed();
  49. mDrbg.Generate(bytes, mPredictionResistant);
  50. }
  51. }
  52. }
  53. public override void NextBytes(byte[] buf, int off, int len)
  54. {
  55. byte[] bytes = new byte[len];
  56. NextBytes(bytes);
  57. Array.Copy(bytes, 0, buf, off, len);
  58. }
  59. public override byte[] GenerateSeed(int numBytes)
  60. {
  61. return EntropyUtilities.GenerateSeed(mDrbg.EntropySource, numBytes);
  62. }
  63. }
  64. }
  65. #pragma warning restore
  66. #endif