summary refs log tree commit diff
path: root/crypto/src/math/ec/multiplier/FpNafMultiplier.cs
blob: 3453e56002b7f7cd822e25d10c43ec0765d3676a (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
namespace Org.BouncyCastle.Math.EC.Multiplier
{
    /**
    * Class implementing the NAF (Non-Adjacent Form) multiplication algorithm.
    */
    internal class FpNafMultiplier
        : ECMultiplier
    {
        /**
        * D.3.2 pg 101
        * @see org.bouncycastle.math.ec.multiplier.ECMultiplier#multiply(org.bouncycastle.math.ec.ECPoint, java.math.BigInteger)
        */
        public ECPoint Multiply(ECPoint p, BigInteger k, PreCompInfo preCompInfo)
        {
            // TODO Probably should try to add this
            // BigInteger e = k.Mod(n); // n == order of p
            BigInteger e = k;
            BigInteger h = e.Multiply(BigInteger.Three);

            ECPoint neg = p.Negate();
            ECPoint R = p;

            for (int i = h.BitLength - 2; i > 0; --i)
            {             
                bool hBit = h.TestBit(i);
                bool eBit = e.TestBit(i);

                if (hBit == eBit)
                {
                    R = R.Twice();
                }
                else
                {
                    R = R.TwicePlus(hBit ? p : neg);
                }
            }

            return R;
        }
    }
}