-
Notifications
You must be signed in to change notification settings - Fork 22
/
ecdh_test.go
104 lines (85 loc) · 1.98 KB
/
ecdh_test.go
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
95
96
97
98
99
100
101
102
103
104
package ecdh
import (
"bytes"
"crypto"
"crypto/elliptic"
"crypto/rand"
"testing"
)
func TestNIST224(t *testing.T) {
testECDH(NewEllipticECDH(elliptic.P224()), t)
}
func TestNIST256(t *testing.T) {
testECDH(NewEllipticECDH(elliptic.P256()), t)
}
func TestNIST384(t *testing.T) {
testECDH(NewEllipticECDH(elliptic.P384()), t)
}
func TestNIST521(t *testing.T) {
testECDH(NewEllipticECDH(elliptic.P521()), t)
}
func TestCurve25519(t *testing.T) {
testECDH(NewCurve25519ECDH(), t)
}
func BenchmarkNIST224(b *testing.B) {
for i := 0; i < b.N; i++ {
testECDH(NewEllipticECDH(elliptic.P224()), b)
}
}
func BenchmarkNIST256(b *testing.B) {
for i := 0; i < b.N; i++ {
testECDH(NewEllipticECDH(elliptic.P256()), b)
}
}
func BenchmarkNIST384(b *testing.B) {
for i := 0; i < b.N; i++ {
testECDH(NewEllipticECDH(elliptic.P384()), b)
}
}
func BenchmarkNIST521(b *testing.B) {
for i := 0; i < b.N; i++ {
testECDH(NewEllipticECDH(elliptic.P521()), b)
}
}
func BenchmarkCurve25519(b *testing.B) {
for i := 0; i < b.N; i++ {
testECDH(NewCurve25519ECDH(), b)
}
}
func testECDH(e ECDH, t testing.TB) {
var privKey1, privKey2 crypto.PrivateKey
var pubKey1, pubKey2 crypto.PublicKey
var pubKey1Buf, pubKey2Buf []byte
var err error
var ok bool
var secret1, secret2 []byte
privKey1, pubKey1, err = e.GenerateKey(rand.Reader)
if err != nil {
t.Error(err)
}
privKey2, pubKey2, err = e.GenerateKey(rand.Reader)
if err != nil {
t.Error(err)
}
pubKey1Buf = e.Marshal(pubKey1)
pubKey2Buf = e.Marshal(pubKey2)
pubKey1, ok = e.Unmarshal(pubKey1Buf)
if !ok {
t.Fatalf("Unmarshal does not work")
}
pubKey2, ok = e.Unmarshal(pubKey2Buf)
if !ok {
t.Fatalf("Unmarshal does not work")
}
secret1, err = e.GenerateSharedSecret(privKey1, pubKey2)
if err != nil {
t.Error(err)
}
secret2, err = e.GenerateSharedSecret(privKey2, pubKey1)
if err != nil {
t.Error(err)
}
if !bytes.Equal(secret1, secret2) {
t.Fatalf("The two shared keys: %d, %d do not match", secret1, secret2)
}
}