-
Notifications
You must be signed in to change notification settings - Fork 12
/
ecdsa_test.go
100 lines (91 loc) · 2.55 KB
/
ecdsa_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
package openssl_test
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"testing"
"github.com/golang-fips/openssl/v2"
"github.com/golang-fips/openssl/v2/bbig"
)
func testAllCurves(t *testing.T, f func(*testing.T, elliptic.Curve)) {
tests := []struct {
name string
curve elliptic.Curve
}{
{"P256", elliptic.P256()},
{"P224", elliptic.P224()},
{"P384", elliptic.P384()},
{"P521", elliptic.P521()},
}
for _, test := range tests {
curve := test.curve
t.Run(test.name, func(t *testing.T) {
t.Parallel()
f(t, curve)
})
}
}
func TestECDSAKeyGeneration(t *testing.T) {
testAllCurves(t, testECDSAKeyGeneration)
}
func testECDSAKeyGeneration(t *testing.T, c elliptic.Curve) {
priv, err := generateKeycurve(c)
if err != nil {
t.Fatal(err)
}
if !c.IsOnCurve(priv.PublicKey.X, priv.PublicKey.Y) {
t.Errorf("public key invalid: %s", err)
}
}
func TestECDSASignAndVerify(t *testing.T) {
testAllCurves(t, testECDSASignAndVerify)
}
func testECDSASignAndVerify(t *testing.T, c elliptic.Curve) {
key, err := generateKeycurve(c)
if err != nil {
t.Fatal(err)
}
msg := []byte("hi!")
hashed := openssl.SHA256(msg)
priv, err := openssl.NewPrivateKeyECDSA(key.Params().Name, bbig.Enc(key.X), bbig.Enc(key.Y), bbig.Enc(key.D))
if err != nil {
t.Fatal(err)
}
pub, err := openssl.NewPublicKeyECDSA(key.Params().Name, bbig.Enc(key.X), bbig.Enc(key.Y))
if err != nil {
t.Fatal(err)
}
signed, err := openssl.SignMarshalECDSA(priv, hashed[:])
if err != nil {
t.Fatal(err)
}
if !openssl.VerifyECDSA(pub, hashed[:], signed) {
t.Errorf("Verify failed")
}
// Alter the signature to intentionally make it invalid. Change the last
// byte (rather than the first) to avoid corrupting the DER encoding, which
// would cause some OpenSSL providers, such as SymCrypt-OpenSSL, to write a
// noisy warning to stderr.
signed[len(signed)-1] ^= 0xff
if openssl.VerifyECDSA(pub, hashed[:], signed) {
t.Errorf("Verify succeeded despite intentionally invalid hash!")
}
signed, err = openssl.HashSignECDSA(priv, crypto.SHA256, msg)
if err != nil {
t.Fatal(err)
}
if !openssl.HashVerifyECDSA(pub, crypto.SHA256, msg, signed) {
t.Errorf("Verify failed")
}
signed[len(signed)-1] ^= 0xff
if openssl.HashVerifyECDSA(pub, crypto.SHA256, msg, signed) {
t.Errorf("Verify failed")
}
}
func generateKeycurve(c elliptic.Curve) (*ecdsa.PrivateKey, error) {
x, y, d, err := openssl.GenerateKeyECDSA(c.Params().Name)
if err != nil {
return nil, err
}
return &ecdsa.PrivateKey{PublicKey: ecdsa.PublicKey{Curve: c, X: bbig.Dec(x), Y: bbig.Dec(y)}, D: bbig.Dec(d)}, nil
}