CryptoApiRandomGenerator.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.Security.Cryptography;
  5. namespace Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng
  6. {
  7. /// <summary>
  8. /// Uses RandomNumberGenerator.Create() to get randomness generator
  9. /// </summary>
  10. public sealed class CryptoApiRandomGenerator
  11. : IRandomGenerator, IDisposable
  12. {
  13. private readonly RandomNumberGenerator m_randomNumberGenerator;
  14. public CryptoApiRandomGenerator()
  15. : this(RandomNumberGenerator.Create())
  16. {
  17. }
  18. public CryptoApiRandomGenerator(RandomNumberGenerator randomNumberGenerator)
  19. {
  20. m_randomNumberGenerator = randomNumberGenerator ??
  21. throw new ArgumentNullException(nameof(randomNumberGenerator));
  22. }
  23. #region IRandomGenerator Members
  24. public void AddSeedMaterial(byte[] seed)
  25. {
  26. // We don't care about the seed
  27. }
  28. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  29. public void AddSeedMaterial(ReadOnlySpan<byte> inSeed)
  30. {
  31. // We don't care about the seed
  32. }
  33. #endif
  34. public void AddSeedMaterial(long seed)
  35. {
  36. // We don't care about the seed
  37. }
  38. public void NextBytes(byte[] bytes)
  39. {
  40. m_randomNumberGenerator.GetBytes(bytes);
  41. }
  42. public void NextBytes(byte[] bytes, int start, int len)
  43. {
  44. #if NETCOREAPP2_0_OR_GREATER || NETSTANDARD2_0_OR_GREATER
  45. m_randomNumberGenerator.GetBytes(bytes, start, len);
  46. #else
  47. if (start < 0)
  48. throw new ArgumentException("Start offset cannot be negative", "start");
  49. if (bytes.Length < (start + len))
  50. throw new ArgumentException("Byte array too small for requested offset and length");
  51. if (bytes.Length == len && start == 0)
  52. {
  53. NextBytes(bytes);
  54. }
  55. else
  56. {
  57. byte[] tmpBuf = new byte[len];
  58. NextBytes(tmpBuf);
  59. Array.Copy(tmpBuf, 0, bytes, start, len);
  60. }
  61. #endif
  62. }
  63. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  64. public void NextBytes(Span<byte> bytes)
  65. {
  66. m_randomNumberGenerator.GetBytes(bytes);
  67. }
  68. #endif
  69. #endregion
  70. #region IDisposable Members
  71. public void Dispose()
  72. {
  73. m_randomNumberGenerator.Dispose();
  74. }
  75. #endregion
  76. }
  77. }
  78. #pragma warning restore
  79. #endif