X931SecureRandom.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Security;
  5. namespace Best.HTTP.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(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. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  31. public override void SetSeed(Span<byte> seed)
  32. {
  33. lock (this)
  34. {
  35. if (mRandomSource != null)
  36. {
  37. this.mRandomSource.SetSeed(seed);
  38. }
  39. }
  40. }
  41. #endif
  42. public override void SetSeed(long seed)
  43. {
  44. lock (this)
  45. {
  46. // this will happen when SecureRandom() is created
  47. if (mRandomSource != null)
  48. {
  49. this.mRandomSource.SetSeed(seed);
  50. }
  51. }
  52. }
  53. public override void NextBytes(byte[] bytes)
  54. {
  55. NextBytes(bytes, 0, bytes.Length);
  56. }
  57. public override void NextBytes(byte[] buf, int off, int len)
  58. {
  59. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  60. NextBytes(buf.AsSpan(off, len));
  61. #else
  62. lock (this)
  63. {
  64. // check if a reseed is required...
  65. if (mDrbg.Generate(buf, off, len, mPredictionResistant) < 0)
  66. {
  67. mDrbg.Reseed();
  68. mDrbg.Generate(buf, off, len, mPredictionResistant);
  69. }
  70. }
  71. #endif
  72. }
  73. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  74. public override void NextBytes(Span<byte> buffer)
  75. {
  76. lock (this)
  77. {
  78. // check if a reseed is required...
  79. if (mDrbg.Generate(buffer, mPredictionResistant) < 0)
  80. {
  81. mDrbg.Reseed();
  82. mDrbg.Generate(buffer, mPredictionResistant);
  83. }
  84. }
  85. }
  86. #endif
  87. public override byte[] GenerateSeed(int numBytes)
  88. {
  89. return EntropyUtilities.GenerateSeed(mDrbg.EntropySource, numBytes);
  90. }
  91. }
  92. }
  93. #pragma warning restore
  94. #endif