CryptoApiRandomGenerator.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #if !(NETCF_1_0 || PORTABLE)
  3. using System;
  4. #if NETFX_CORE
  5. using Windows.Security.Cryptography;
  6. #else
  7. using System.Security.Cryptography;
  8. #endif
  9. namespace Org.BouncyCastle.Crypto.Prng
  10. {
  11. /// <summary>
  12. /// Uses Microsoft's RNGCryptoServiceProvider
  13. /// </summary>
  14. public class CryptoApiRandomGenerator
  15. : IRandomGenerator
  16. {
  17. #if !NETFX_CORE
  18. private readonly RandomNumberGenerator rndProv;
  19. #endif
  20. public CryptoApiRandomGenerator()
  21. #if !NETFX_CORE
  22. : this(new RNGCryptoServiceProvider())
  23. #endif
  24. {
  25. }
  26. #if !NETFX_CORE
  27. public CryptoApiRandomGenerator(RandomNumberGenerator rng)
  28. {
  29. this.rndProv = rng;
  30. }
  31. #endif
  32. #region IRandomGenerator Members
  33. public virtual void AddSeedMaterial(byte[] seed)
  34. {
  35. // We don't care about the seed
  36. }
  37. public virtual void AddSeedMaterial(long seed)
  38. {
  39. // We don't care about the seed
  40. }
  41. public virtual void NextBytes(byte[] bytes)
  42. {
  43. #if NETFX_CORE
  44. var buffer = CryptographicBuffer.GenerateRandom((uint)bytes.Length);
  45. byte[] finalBytes = null;
  46. CryptographicBuffer.CopyToByteArray(buffer, out finalBytes);
  47. finalBytes.CopyTo(bytes, 0);
  48. #else
  49. rndProv.GetBytes(bytes);
  50. #endif
  51. }
  52. public virtual void NextBytes(byte[] bytes, int start, int len)
  53. {
  54. if (start < 0)
  55. throw new ArgumentException("Start offset cannot be negative", "start");
  56. if (bytes.Length < (start + len))
  57. throw new ArgumentException("Byte array too small for requested offset and length");
  58. if (bytes.Length == len && start == 0)
  59. {
  60. NextBytes(bytes);
  61. }
  62. else
  63. {
  64. #if NETFX_CORE
  65. byte[] tmpBuf = null;
  66. var buffer = CryptographicBuffer.GenerateRandom((uint)bytes.Length);
  67. CryptographicBuffer.CopyToByteArray(buffer, out tmpBuf);
  68. #else
  69. byte[] tmpBuf = new byte[len];
  70. NextBytes(tmpBuf);
  71. #endif
  72. Array.Copy(tmpBuf, 0, bytes, start, len);
  73. }
  74. }
  75. #endregion
  76. }
  77. }
  78. #endif
  79. #endif