CipherKeyGenerator.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Security;
  5. namespace Best.HTTP.SecureProtocol.Org.BouncyCastle.Crypto
  6. {
  7. /**
  8. * The base class for symmetric, or secret, cipher key generators.
  9. */
  10. public class CipherKeyGenerator
  11. {
  12. protected internal SecureRandom random;
  13. protected internal int strength;
  14. private bool uninitialised = true;
  15. private int defaultStrength;
  16. public CipherKeyGenerator()
  17. {
  18. }
  19. internal CipherKeyGenerator(
  20. int defaultStrength)
  21. {
  22. if (defaultStrength < 1)
  23. throw new ArgumentException("strength must be a positive value", "defaultStrength");
  24. this.defaultStrength = defaultStrength;
  25. }
  26. public int DefaultStrength
  27. {
  28. get { return defaultStrength; }
  29. }
  30. /**
  31. * initialise the key generator.
  32. *
  33. * @param param the parameters to be used for key generation
  34. */
  35. public void Init(KeyGenerationParameters parameters)
  36. {
  37. if (parameters == null)
  38. throw new ArgumentNullException(nameof(parameters));
  39. this.uninitialised = false;
  40. EngineInit(parameters);
  41. }
  42. protected virtual void EngineInit(KeyGenerationParameters parameters)
  43. {
  44. this.random = parameters.Random;
  45. this.strength = (parameters.Strength + 7) / 8;
  46. }
  47. /**
  48. * Generate a secret key.
  49. *
  50. * @return a byte array containing the key value.
  51. */
  52. public byte[] GenerateKey()
  53. {
  54. if (uninitialised)
  55. {
  56. if (defaultStrength < 1)
  57. throw new InvalidOperationException("Generator has not been initialised");
  58. uninitialised = false;
  59. EngineInit(new KeyGenerationParameters(CryptoServicesRegistrar.GetSecureRandom(), defaultStrength));
  60. }
  61. return EngineGenerateKey();
  62. }
  63. protected virtual byte[] EngineGenerateKey()
  64. {
  65. return SecureRandom.GetNextBytes(random, strength);
  66. }
  67. }
  68. }
  69. #pragma warning restore
  70. #endif