summaryrefslogtreecommitdiffstats
path: root/src/crypto/elliptic/internal/nistec/nistec_test.go
blob: 4eae998c5d7be46634889027f94638a6cb724fc5 (plain)
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package nistec_test

import (
	"crypto/elliptic/internal/nistec"
	"math/rand"
	"os"
	"strings"
	"testing"
)

func TestAllocations(t *testing.T) {
	if strings.HasSuffix(os.Getenv("GO_BUILDER_NAME"), "-noopt") {
		t.Skip("skipping allocations test without relevant optimizations")
	}
	t.Run("P224", func(t *testing.T) {
		if allocs := testing.AllocsPerRun(100, func() {
			p := nistec.NewP224Generator()
			scalar := make([]byte, 66)
			rand.Read(scalar)
			p.ScalarMult(p, scalar)
			out := p.Bytes()
			if _, err := p.SetBytes(out); err != nil {
				t.Fatal(err)
			}
		}); allocs > 0 {
			t.Errorf("expected zero allocations, got %0.1f", allocs)
		}
	})
	t.Run("P384", func(t *testing.T) {
		if allocs := testing.AllocsPerRun(100, func() {
			p := nistec.NewP384Generator()
			scalar := make([]byte, 66)
			rand.Read(scalar)
			p.ScalarMult(p, scalar)
			out := p.Bytes()
			if _, err := p.SetBytes(out); err != nil {
				t.Fatal(err)
			}
		}); allocs > 0 {
			t.Errorf("expected zero allocations, got %0.1f", allocs)
		}
	})
	t.Run("P521", func(t *testing.T) {
		if allocs := testing.AllocsPerRun(100, func() {
			p := nistec.NewP521Generator()
			scalar := make([]byte, 66)
			rand.Read(scalar)
			p.ScalarMult(p, scalar)
			out := p.Bytes()
			if _, err := p.SetBytes(out); err != nil {
				t.Fatal(err)
			}
		}); allocs > 0 {
			t.Errorf("expected zero allocations, got %0.1f", allocs)
		}
	})
}

func BenchmarkScalarMult(b *testing.B) {
	b.Run("P224", func(b *testing.B) {
		scalar := make([]byte, 66)
		rand.Read(scalar)
		p := nistec.NewP224Generator()
		b.ReportAllocs()
		b.ResetTimer()
		for i := 0; i < b.N; i++ {
			p.ScalarMult(p, scalar)
		}
	})
	b.Run("P384", func(b *testing.B) {
		scalar := make([]byte, 66)
		rand.Read(scalar)
		p := nistec.NewP384Generator()
		b.ReportAllocs()
		b.ResetTimer()
		for i := 0; i < b.N; i++ {
			p.ScalarMult(p, scalar)
		}
	})
	b.Run("P521", func(b *testing.B) {
		scalar := make([]byte, 66)
		rand.Read(scalar)
		p := nistec.NewP521Generator()
		b.ReportAllocs()
		b.ResetTimer()
		for i := 0; i < b.N; i++ {
			p.ScalarMult(p, scalar)
		}
	})
}