CipherKeyGenerator.cs 1.8 KB

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