SP800SecureRandom.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng.Drbg;
  5. using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
  6. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng
  7. {
  8. public class SP800SecureRandom
  9. : SecureRandom
  10. {
  11. private readonly IDrbgProvider mDrbgProvider;
  12. private readonly bool mPredictionResistant;
  13. private readonly SecureRandom mRandomSource;
  14. private readonly IEntropySource mEntropySource;
  15. private ISP80090Drbg mDrbg;
  16. internal SP800SecureRandom(SecureRandom randomSource, IEntropySource entropySource, IDrbgProvider drbgProvider, bool predictionResistant)
  17. : base((IRandomGenerator)null)
  18. {
  19. this.mRandomSource = randomSource;
  20. this.mEntropySource = entropySource;
  21. this.mDrbgProvider = drbgProvider;
  22. this.mPredictionResistant = predictionResistant;
  23. }
  24. public override void SetSeed(byte[] seed)
  25. {
  26. lock (this)
  27. {
  28. if (mRandomSource != null)
  29. {
  30. this.mRandomSource.SetSeed(seed);
  31. }
  32. }
  33. }
  34. public override void SetSeed(long seed)
  35. {
  36. lock (this)
  37. {
  38. // this will happen when SecureRandom() is created
  39. if (mRandomSource != null)
  40. {
  41. this.mRandomSource.SetSeed(seed);
  42. }
  43. }
  44. }
  45. public override void NextBytes(byte[] bytes)
  46. {
  47. lock (this)
  48. {
  49. if (mDrbg == null)
  50. {
  51. mDrbg = mDrbgProvider.Get(mEntropySource);
  52. }
  53. // check if a reseed is required...
  54. if (mDrbg.Generate(bytes, null, mPredictionResistant) < 0)
  55. {
  56. mDrbg.Reseed(null);
  57. mDrbg.Generate(bytes, null, mPredictionResistant);
  58. }
  59. }
  60. }
  61. public override void NextBytes(byte[] buf, int off, int len)
  62. {
  63. byte[] bytes = new byte[len];
  64. NextBytes(bytes);
  65. Array.Copy(bytes, 0, buf, off, len);
  66. }
  67. public override byte[] GenerateSeed(int numBytes)
  68. {
  69. return EntropyUtilities.GenerateSeed(mEntropySource, numBytes);
  70. }
  71. /// <summary>Force a reseed of the DRBG.</summary>
  72. /// <param name="additionalInput">optional additional input</param>
  73. public virtual void Reseed(byte[] additionalInput)
  74. {
  75. lock (this)
  76. {
  77. if (mDrbg == null)
  78. {
  79. mDrbg = mDrbgProvider.Get(mEntropySource);
  80. }
  81. mDrbg.Reseed(additionalInput);
  82. }
  83. }
  84. }
  85. }
  86. #pragma warning restore
  87. #endif