DHKeyGeneratorHelper.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. using System;
  3. using Org.BouncyCastle.Crypto.Parameters;
  4. using Org.BouncyCastle.Math;
  5. using Org.BouncyCastle.Math.EC.Multiplier;
  6. using Org.BouncyCastle.Security;
  7. using Org.BouncyCastle.Utilities;
  8. namespace Org.BouncyCastle.Crypto.Generators
  9. {
  10. class DHKeyGeneratorHelper
  11. {
  12. internal static readonly DHKeyGeneratorHelper Instance = new DHKeyGeneratorHelper();
  13. private DHKeyGeneratorHelper()
  14. {
  15. }
  16. internal BigInteger CalculatePrivate(
  17. DHParameters dhParams,
  18. SecureRandom random)
  19. {
  20. int limit = dhParams.L;
  21. if (limit != 0)
  22. {
  23. int minWeight = limit >> 2;
  24. for (;;)
  25. {
  26. BigInteger x = new BigInteger(limit, random).SetBit(limit - 1);
  27. if (WNafUtilities.GetNafWeight(x) >= minWeight)
  28. {
  29. return x;
  30. }
  31. }
  32. }
  33. BigInteger min = BigInteger.Two;
  34. int m = dhParams.M;
  35. if (m != 0)
  36. {
  37. min = BigInteger.One.ShiftLeft(m - 1);
  38. }
  39. BigInteger q = dhParams.Q;
  40. if (q == null)
  41. {
  42. q = dhParams.P;
  43. }
  44. BigInteger max = q.Subtract(BigInteger.Two);
  45. {
  46. int minWeight = max.BitLength >> 2;
  47. for (;;)
  48. {
  49. BigInteger x = BigIntegers.CreateRandomInRange(min, max, random);
  50. if (WNafUtilities.GetNafWeight(x) >= minWeight)
  51. {
  52. return x;
  53. }
  54. }
  55. }
  56. }
  57. internal BigInteger CalculatePublic(
  58. DHParameters dhParams,
  59. BigInteger x)
  60. {
  61. return dhParams.G.ModPow(x, dhParams.P);
  62. }
  63. }
  64. }
  65. #endif