1// Copyright 2012 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package curve25519
6
7import (
8	"bytes"
9	"crypto/rand"
10	"fmt"
11	"testing"
12)
13
14const expectedHex = "89161fde887b2b53de549af483940106ecc114d6982daa98256de23bdf77661a"
15
16func TestX25519Basepoint(t *testing.T) {
17	x := make([]byte, 32)
18	x[0] = 1
19
20	for i := 0; i < 200; i++ {
21		var err error
22		x, err = X25519(x, Basepoint)
23		if err != nil {
24			t.Fatal(err)
25		}
26	}
27
28	result := fmt.Sprintf("%x", x)
29	if result != expectedHex {
30		t.Errorf("incorrect result: got %s, want %s", result, expectedHex)
31	}
32}
33
34func TestLowOrderPoints(t *testing.T) {
35	scalar := make([]byte, ScalarSize)
36	if _, err := rand.Read(scalar); err != nil {
37		t.Fatal(err)
38	}
39	for i, p := range lowOrderPoints {
40		out, err := X25519(scalar, p)
41		if err == nil {
42			t.Errorf("%d: expected error, got nil", i)
43		}
44		if out != nil {
45			t.Errorf("%d: expected nil output, got %x", i, out)
46		}
47	}
48}
49
50func TestTestVectors(t *testing.T) {
51	t.Run("Generic", func(t *testing.T) { testTestVectors(t, scalarMultGeneric) })
52	t.Run("Native", func(t *testing.T) { testTestVectors(t, ScalarMult) })
53	t.Run("X25519", func(t *testing.T) {
54		testTestVectors(t, func(dst, scalar, point *[32]byte) {
55			out, err := X25519(scalar[:], point[:])
56			if err != nil {
57				t.Fatal(err)
58			}
59			copy(dst[:], out)
60		})
61	})
62}
63
64func testTestVectors(t *testing.T, scalarMult func(dst, scalar, point *[32]byte)) {
65	for _, tv := range testVectors {
66		var got [32]byte
67		scalarMult(&got, &tv.In, &tv.Base)
68		if !bytes.Equal(got[:], tv.Expect[:]) {
69			t.Logf("    in = %x", tv.In)
70			t.Logf("  base = %x", tv.Base)
71			t.Logf("   got = %x", got)
72			t.Logf("expect = %x", tv.Expect)
73			t.Fail()
74		}
75	}
76}
77
78// TestHighBitIgnored tests the following requirement in RFC 7748:
79//
80//	When receiving such an array, implementations of X25519 (but not X448) MUST
81//	mask the most significant bit in the final byte.
82//
83// Regression test for issue #30095.
84func TestHighBitIgnored(t *testing.T) {
85	var s, u [32]byte
86	rand.Read(s[:])
87	rand.Read(u[:])
88
89	var hi0, hi1 [32]byte
90
91	u[31] &= 0x7f
92	ScalarMult(&hi0, &s, &u)
93
94	u[31] |= 0x80
95	ScalarMult(&hi1, &s, &u)
96
97	if !bytes.Equal(hi0[:], hi1[:]) {
98		t.Errorf("high bit of group point should not affect result")
99	}
100}
101
102func BenchmarkScalarBaseMult(b *testing.B) {
103	var in, out [32]byte
104	in[0] = 1
105
106	b.SetBytes(32)
107	for i := 0; i < b.N; i++ {
108		ScalarBaseMult(&out, &in)
109	}
110}
111