BasicEntropySourceProvider.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
  5. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng
  6. {
  7. /**
  8. * An EntropySourceProvider where entropy generation is based on a SecureRandom output using SecureRandom.generateSeed().
  9. */
  10. public class BasicEntropySourceProvider
  11. : IEntropySourceProvider
  12. {
  13. private readonly SecureRandom mSecureRandom;
  14. private readonly bool mPredictionResistant;
  15. /**
  16. * Create a entropy source provider based on the passed in SecureRandom.
  17. *
  18. * @param secureRandom the SecureRandom to base EntropySource construction on.
  19. * @param isPredictionResistant boolean indicating if the SecureRandom is based on prediction resistant entropy or not (true if it is).
  20. */
  21. public BasicEntropySourceProvider(SecureRandom secureRandom, bool isPredictionResistant)
  22. {
  23. mSecureRandom = secureRandom;
  24. mPredictionResistant = isPredictionResistant;
  25. }
  26. /**
  27. * Return an entropy source that will create bitsRequired bits of entropy on
  28. * each invocation of getEntropy().
  29. *
  30. * @param bitsRequired size (in bits) of entropy to be created by the provided source.
  31. * @return an EntropySource that generates bitsRequired bits of entropy on each call to its getEntropy() method.
  32. */
  33. public IEntropySource Get(int bitsRequired)
  34. {
  35. return new BasicEntropySource(mSecureRandom, mPredictionResistant, bitsRequired);
  36. }
  37. private class BasicEntropySource
  38. : IEntropySource
  39. {
  40. private readonly SecureRandom mSecureRandom;
  41. private readonly bool mPredictionResistant;
  42. private readonly int mEntropySize;
  43. internal BasicEntropySource(SecureRandom secureRandom, bool predictionResistant, int entropySize)
  44. {
  45. this.mSecureRandom = secureRandom;
  46. this.mPredictionResistant = predictionResistant;
  47. this.mEntropySize = entropySize;
  48. }
  49. bool IEntropySource.IsPredictionResistant
  50. {
  51. get { return mPredictionResistant; }
  52. }
  53. byte[] IEntropySource.GetEntropy()
  54. {
  55. // TODO[FIPS] Not all SecureRandom implementations are considered valid entropy sources
  56. return SecureRandom.GetNextBytes(mSecureRandom, (mEntropySize + 7) / 8);
  57. }
  58. int IEntropySource.EntropySize
  59. {
  60. get { return mEntropySize; }
  61. }
  62. }
  63. }
  64. }
  65. #pragma warning restore
  66. #endif