summary refs log tree commit diff
path: root/crypto/src/math/ec/multiplier/MixedNafR2LMultiplier.cs
blob: a4c201832c753a41c0bdbf53a6f1cb84a026488a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using System;

namespace Org.BouncyCastle.Math.EC.Multiplier
{
    /**
     * Class implementing the NAF (Non-Adjacent Form) multiplication algorithm (right-to-left) using
     * mixed coordinates.
     */
    public class MixedNafR2LMultiplier 
        : AbstractECMultiplier
    {
        protected readonly int additionCoord, doublingCoord;

        /**
         * By default, addition will be done in Jacobian coordinates, and doubling will be done in
         * Modified Jacobian coordinates (independent of the original coordinate system of each point).
         */
        public MixedNafR2LMultiplier()
            : this(ECCurve.COORD_JACOBIAN, ECCurve.COORD_JACOBIAN_MODIFIED)
        {
        }

        public MixedNafR2LMultiplier(int additionCoord, int doublingCoord)
        {
            this.additionCoord = additionCoord;
            this.doublingCoord = doublingCoord;
        }

        protected override ECPoint MultiplyPositive(ECPoint p, BigInteger k)
        {
            ECCurve curveOrig = p.Curve;

            ECCurve curveAdd = ConfigureCurve(curveOrig, additionCoord);
            ECCurve curveDouble = ConfigureCurve(curveOrig, doublingCoord);

            int[] naf = WNafUtilities.GenerateCompactNaf(k);

            ECPoint Ra = curveAdd.Infinity;
            ECPoint Td = curveDouble.ImportPoint(p);

            int zeroes = 0;
            for (int i = 0; i < naf.Length; ++i)
            {
                int ni = naf[i];
                int digit = ni >> 16;
                zeroes += ni & 0xFFFF;

                Td = Td.TimesPow2(zeroes);

                ECPoint Tj = curveAdd.ImportPoint(Td);
                if (digit < 0)
                {
                    Tj = Tj.Negate();
                }

                Ra = Ra.Add(Tj);

                zeroes = 1;
            }

            return curveOrig.ImportPoint(Ra);
        }

        protected virtual ECCurve ConfigureCurve(ECCurve c, int coord)
        {
            if (c.CoordinateSystem == coord)
                return c;

            if (!c.SupportsCoordinateSystem(coord))
                throw new ArgumentException("Coordinate system " + coord + " not supported by this curve", "coord");

            return c.Configure().SetCoordinateSystem(coord).Create();
        }
    }
}