CryptoApiEntropySourceProvider.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. public class CryptoApiEntropySourceProvider
  9. : IEntropySourceProvider
  10. {
  11. private readonly RandomNumberGenerator mRng;
  12. private readonly bool mPredictionResistant;
  13. public CryptoApiEntropySourceProvider()
  14. : this(RandomNumberGenerator.Create(), true)
  15. {
  16. }
  17. public CryptoApiEntropySourceProvider(RandomNumberGenerator rng, bool isPredictionResistant)
  18. {
  19. if (rng == null)
  20. throw new ArgumentNullException("rng");
  21. mRng = rng;
  22. mPredictionResistant = isPredictionResistant;
  23. }
  24. public IEntropySource Get(int bitsRequired)
  25. {
  26. return new CryptoApiEntropySource(mRng, mPredictionResistant, bitsRequired);
  27. }
  28. private class CryptoApiEntropySource
  29. : IEntropySource
  30. {
  31. private readonly RandomNumberGenerator mRng;
  32. private readonly bool mPredictionResistant;
  33. private readonly int mEntropySize;
  34. internal CryptoApiEntropySource(RandomNumberGenerator rng, bool predictionResistant, int entropySize)
  35. {
  36. this.mRng = rng;
  37. this.mPredictionResistant = predictionResistant;
  38. this.mEntropySize = entropySize;
  39. }
  40. #region IEntropySource Members
  41. bool IEntropySource.IsPredictionResistant
  42. {
  43. get { return mPredictionResistant; }
  44. }
  45. byte[] IEntropySource.GetEntropy()
  46. {
  47. byte[] result = new byte[(mEntropySize + 7) / 8];
  48. mRng.GetBytes(result);
  49. return result;
  50. }
  51. int IEntropySource.EntropySize
  52. {
  53. get { return mEntropySize; }
  54. }
  55. #endregion
  56. }
  57. }
  58. }
  59. #endif
  60. #pragma warning restore
  61. #endif