MixedNafR2LMultiplier.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Multiplier
  5. {
  6. /**
  7. * Class implementing the NAF (Non-Adjacent Form) multiplication algorithm (right-to-left) using
  8. * mixed coordinates.
  9. */
  10. public class MixedNafR2LMultiplier
  11. : AbstractECMultiplier
  12. {
  13. protected readonly int additionCoord, doublingCoord;
  14. /**
  15. * By default, addition will be done in Jacobian coordinates, and doubling will be done in
  16. * Modified Jacobian coordinates (independent of the original coordinate system of each point).
  17. */
  18. public MixedNafR2LMultiplier()
  19. : this(ECCurve.COORD_JACOBIAN, ECCurve.COORD_JACOBIAN_MODIFIED)
  20. {
  21. }
  22. public MixedNafR2LMultiplier(int additionCoord, int doublingCoord)
  23. {
  24. this.additionCoord = additionCoord;
  25. this.doublingCoord = doublingCoord;
  26. }
  27. protected override ECPoint MultiplyPositive(ECPoint p, BigInteger k)
  28. {
  29. ECCurve curveOrig = p.Curve;
  30. ECCurve curveAdd = ConfigureCurve(curveOrig, additionCoord);
  31. ECCurve curveDouble = ConfigureCurve(curveOrig, doublingCoord);
  32. int[] naf = WNafUtilities.GenerateCompactNaf(k);
  33. ECPoint Ra = curveAdd.Infinity;
  34. ECPoint Td = curveDouble.ImportPoint(p);
  35. int zeroes = 0;
  36. for (int i = 0; i < naf.Length; ++i)
  37. {
  38. int ni = naf[i];
  39. int digit = ni >> 16;
  40. zeroes += ni & 0xFFFF;
  41. Td = Td.TimesPow2(zeroes);
  42. ECPoint Tj = curveAdd.ImportPoint(Td);
  43. if (digit < 0)
  44. {
  45. Tj = Tj.Negate();
  46. }
  47. Ra = Ra.Add(Tj);
  48. zeroes = 1;
  49. }
  50. return curveOrig.ImportPoint(Ra);
  51. }
  52. protected virtual ECCurve ConfigureCurve(ECCurve c, int coord)
  53. {
  54. if (c.CoordinateSystem == coord)
  55. return c;
  56. if (!c.SupportsCoordinateSystem(coord))
  57. throw new ArgumentException("Coordinate system " + coord + " not supported by this curve", "coord");
  58. return c.Configure().SetCoordinateSystem(coord).Create();
  59. }
  60. }
  61. }
  62. #pragma warning restore
  63. #endif