DHKeyGeneratorHelper.cs 2.1 KB

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