Optimized ScalMul to be not recursive

This commit is contained in:
Thorsten Sommer 2020-01-06 23:55:51 +01:00
parent 77709309ad
commit 5424f5b75c

View File

@ -58,19 +58,36 @@ namespace Ed25519
public readonly EdPoint ScalarMul(BigInteger e) public readonly EdPoint ScalarMul(BigInteger e)
{ {
if (e.Equals(BigInteger.Zero)) var numberOperations = (int) Math.Ceiling(BigInteger.Log(e, 2)) + 1;
var series = new bool[numberOperations];
var previousNumber = e;
for (var n = 0; n < numberOperations; n++)
{ {
return new EdPoint if (n == 0)
{ {
X = BigInteger.Zero, series[n] = !e.IsEven;
Y = BigInteger.One, continue;
}; }
var number = BigInteger.Divide(previousNumber, Constants.TWO);
series[n] = !number.IsEven;
previousNumber = number;
} }
var q = this.ScalarMul(e / Constants.TWO); var result = new EdPoint
q = q.EdwardsSquare(); {
X = BigInteger.Zero,
Y = BigInteger.One,
};
return e.IsEven ? q : q.Edwards(this); for (var n = numberOperations - 2; n >= 0; n--)
{
result = result.EdwardsSquare();
if (series[n])
result = result.Edwards(this);
}
return result;
} }
public EdPoint EdwardsSquare() public EdPoint EdwardsSquare()