DesEdeKeyGenerator.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  5. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
  6. {
  7. public class DesEdeKeyGenerator
  8. : DesKeyGenerator
  9. {
  10. public DesEdeKeyGenerator()
  11. {
  12. }
  13. internal DesEdeKeyGenerator(
  14. int defaultStrength)
  15. : base(defaultStrength)
  16. {
  17. }
  18. /**
  19. * initialise the key generator - if strength is set to zero
  20. * the key Generated will be 192 bits in size, otherwise
  21. * strength can be 128 or 192 (or 112 or 168 if you don't count
  22. * parity bits), depending on whether you wish to do 2-key or 3-key
  23. * triple DES.
  24. *
  25. * @param param the parameters to be used for key generation
  26. */
  27. protected override void engineInit(
  28. KeyGenerationParameters parameters)
  29. {
  30. this.random = parameters.Random;
  31. this.strength = (parameters.Strength + 7) / 8;
  32. if (strength == 0 || strength == (168 / 8))
  33. {
  34. strength = DesEdeParameters.DesEdeKeyLength;
  35. }
  36. else if (strength == (112 / 8))
  37. {
  38. strength = 2 * DesEdeParameters.DesKeyLength;
  39. }
  40. else if (strength != DesEdeParameters.DesEdeKeyLength
  41. && strength != (2 * DesEdeParameters.DesKeyLength))
  42. {
  43. throw new ArgumentException("DESede key must be "
  44. + (DesEdeParameters.DesEdeKeyLength * 8) + " or "
  45. + (2 * 8 * DesEdeParameters.DesKeyLength)
  46. + " bits long.");
  47. }
  48. }
  49. protected override byte[] engineGenerateKey()
  50. {
  51. byte[] newKey = new byte[strength];
  52. do
  53. {
  54. random.NextBytes(newKey);
  55. DesEdeParameters.SetOddParity(newKey);
  56. }
  57. while (DesEdeParameters.IsWeakKey(newKey, 0, newKey.Length) || !DesEdeParameters.IsRealEdeKey(newKey, 0));
  58. return newKey;
  59. }
  60. }
  61. }
  62. #pragma warning restore
  63. #endif