From 968377f9c551ce662bf7ab7f288fe8557a9dc3f5 Mon Sep 17 00:00:00 2001 From: George Tankersley Date: Mon, 28 Jan 2019 09:32:56 -0500 Subject: [PATCH] ed25519: fix ScalarMult and improve test to catch the bug (#1) --- ed25519.go | 2 +- ed25519_test.go | 41 +++++++++++++++++------------------------ 2 files changed, 18 insertions(+), 25 deletions(-) diff --git a/ed25519.go b/ed25519.go index 7419f81..4a2ecfa 100644 --- a/ed25519.go +++ b/ed25519.go @@ -125,7 +125,7 @@ func (curve ed25519Curve) ScalarMult(x1, y1 *big.Int, k []byte) (x, y *big.Int) r0.Double(&r0) } else { r0.Add(&r0, &r1) - r1.Double(&r0) + r1.Double(&r1) } } diff --git a/ed25519_test.go b/ed25519_test.go index 1949df1..26026c9 100644 --- a/ed25519_test.go +++ b/ed25519_test.go @@ -104,35 +104,28 @@ func BenchmarkDouble(b *testing.B) { func TestScalarMult(t *testing.T) { ed := Ed25519() - x, y := ed.Params().Gx, ed.Params().Gy + Bx, By := ed.Params().Gx, ed.Params().Gy + var rX, rY, accX, accY = new(big.Int), new(big.Int), new(big.Int), new(big.Int) - twoX, twoY := ed.ScalarMult(x, y, big.NewInt(2).Bytes()) - xPlusX, yPlusY := ed.Add(x, y, x, y) + for i := 1; i <= 1024; i++ { + rX, rY = ed.ScalarMult(Bx, By, big.NewInt(int64(i)).Bytes()) + if i == 0 && (rX.Cmp(Bx) != 0 || rY.Cmp(By) != 0) { + t.Error("bad ScalarMul") + } + accX.Set(Bx) + accY.Set(By) + for j := 1; j < i; j++ { + accX, accY = ed.Add(accX, accY, Bx, By) + } - if !ed.IsOnCurve(twoX, twoY) { - t.Error("2*B is not on the curve") - } + if !ed.IsOnCurve(rX, rY) || !ed.IsOnCurve(accX, accY) { + t.Error("not on the curve") + } - if twoX.Cmp(xPlusX) != 0 || twoY.Cmp(yPlusY) != 0 { - t.Errorf("2*B != B+B") - } - - // TODO: fuzz like it's going out of style - if !testing.Short() { - buf := make([]byte, 32) - for i := 0; i < 1000; i++ { - _, err := io.ReadFull(rand.Reader, buf) - if err != nil { - t.Fatal(err) - } - randX, randY := ed.ScalarMult(x, y, buf) - - if !ed.IsOnCurve(randX, randY) { - t.Errorf("scalarMult return off-curve point for scalar %x", buf) - } + if rX.Cmp(accX) != 0 || rY.Cmp(accY) != 0 { + t.Errorf("inconsistent ScalarMult: %x", i) } } - } func BenchmarkScalarMult(b *testing.B) {