CryptoApiRandomGenerator.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. #if !(NETCF_1_0 || PORTABLE || NETFX_CORE)
  4. using System;
  5. using System.Security.Cryptography;
  6. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng
  7. {
  8. /// <summary>
  9. /// Uses RandomNumberGenerator.Create() to get randomness generator
  10. /// </summary>
  11. public class CryptoApiRandomGenerator
  12. : IRandomGenerator
  13. {
  14. private readonly RandomNumberGenerator rndProv;
  15. public CryptoApiRandomGenerator()
  16. : this(RandomNumberGenerator.Create())
  17. {
  18. }
  19. public CryptoApiRandomGenerator(RandomNumberGenerator rng)
  20. {
  21. this.rndProv = rng;
  22. }
  23. #region IRandomGenerator Members
  24. public virtual void AddSeedMaterial(byte[] seed)
  25. {
  26. // We don't care about the seed
  27. }
  28. public virtual void AddSeedMaterial(long seed)
  29. {
  30. // We don't care about the seed
  31. }
  32. public virtual void NextBytes(byte[] bytes)
  33. {
  34. rndProv.GetBytes(bytes);
  35. }
  36. public virtual void NextBytes(byte[] bytes, int start, int len)
  37. {
  38. if (start < 0)
  39. throw new ArgumentException("Start offset cannot be negative", "start");
  40. if (bytes.Length < (start + len))
  41. throw new ArgumentException("Byte array too small for requested offset and length");
  42. if (bytes.Length == len && start == 0)
  43. {
  44. NextBytes(bytes);
  45. }
  46. else
  47. {
  48. byte[] tmpBuf = new byte[len];
  49. NextBytes(tmpBuf);
  50. Array.Copy(tmpBuf, 0, bytes, start, len);
  51. }
  52. }
  53. #endregion
  54. }
  55. }
  56. #endif
  57. #pragma warning restore
  58. #endif