File: curve4Q_test.go

package info (click to toggle)
golang-github-cloudflare-circl 1.0.0%2B20200724-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 5,788 kB
  • sloc: asm: 19,418; ansic: 1,289; makefile: 54
file content (78 lines) | stat: -rw-r--r-- 1,752 bytes parent folder | download | duplicates (4)
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
package curve4q

import (
	"bytes"
	"crypto/rand"
	"fmt"
	"io"
	"testing"

	"github.com/cloudflare/circl/internal/test"
)

func TestDH(t *testing.T) {
	var secretAlice, publicAlice, sharedAlice Key
	var secretBob, publicBob, sharedBob Key
	testTimes := 1 << 10

	for i := 0; i < testTimes; i++ {
		_, _ = rand.Read(secretAlice[:])
		_, _ = rand.Read(secretBob[:])

		KeyGen(&publicAlice, &secretAlice)
		KeyGen(&publicBob, &secretBob)

		if ok := Shared(&sharedAlice, &secretAlice, &publicBob); !ok {
			test.ReportError(t, ok, true, secretAlice, publicBob)
		}
		if ok := Shared(&sharedBob, &secretBob, &publicAlice); !ok {
			test.ReportError(t, ok, true, secretBob, publicAlice)
		}

		got := sharedAlice
		want := sharedBob
		if !bytes.Equal(got[:], want[:]) {
			test.ReportError(t, got, want, secretAlice, secretBob)
		}
	}
}

func BenchmarkDH(b *testing.B) {
	var secret, public, shared Key
	_, _ = rand.Read(secret[:])
	_, _ = rand.Read(public[:])

	b.Run("keygen", func(b *testing.B) {
		for i := 0; i < b.N; i++ {
			KeyGen(&public, &secret)
		}
	})
	b.Run("shared", func(b *testing.B) {
		for i := 0; i < b.N; i++ {
			Shared(&shared, &secret, &public)
		}
	})
}

func ExampleKey() {
	var AliceSecret, BobSecret,
		AlicePublic, BobPublic,
		AliceShared, BobShared Key

	// Generating Alice's secret and public keys
	_, _ = io.ReadFull(rand.Reader, AliceSecret[:])
	KeyGen(&AlicePublic, &AliceSecret)

	// Generating Bob's secret and public keys
	_, _ = io.ReadFull(rand.Reader, BobSecret[:])
	KeyGen(&BobPublic, &BobSecret)

	// Deriving Alice's shared key
	Shared(&AliceShared, &AliceSecret, &BobPublic)

	// Deriving Bob's shared key
	Shared(&BobShared, &BobSecret, &AlicePublic)

	fmt.Println(AliceShared == BobShared)
	// Output: true
}