CipherKeyGenerator.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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
  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(
  36. KeyGenerationParameters parameters)
  37. {
  38. if (parameters == null)
  39. throw new ArgumentNullException("parameters");
  40. this.uninitialised = false;
  41. engineInit(parameters);
  42. }
  43. protected virtual void engineInit(
  44. KeyGenerationParameters parameters)
  45. {
  46. this.random = parameters.Random;
  47. this.strength = (parameters.Strength + 7) / 8;
  48. }
  49. /**
  50. * Generate a secret key.
  51. *
  52. * @return a byte array containing the key value.
  53. */
  54. public byte[] GenerateKey()
  55. {
  56. if (uninitialised)
  57. {
  58. if (defaultStrength < 1)
  59. throw new InvalidOperationException("Generator has not been initialised");
  60. uninitialised = false;
  61. engineInit(new KeyGenerationParameters(new SecureRandom(), defaultStrength));
  62. }
  63. return engineGenerateKey();
  64. }
  65. protected virtual byte[] engineGenerateKey()
  66. {
  67. return SecureRandom.GetNextBytes(random, strength);
  68. }
  69. }
  70. }
  71. #pragma warning restore
  72. #endif