Debian Codegraph @

openpgp/ecdsa/ecdsa_test.go

raw
1 // Package ecdsa implements ECDSA signature, suitable for OpenPGP,
2 // as specified in RFC 6637, section 5.
3 package ecdsa
4
5 import (
6 "crypto/rand"
7 "io"
8 "math/big"
9 "testing"
10
11 "github.com/ProtonMail/go-crypto/openpgp/internal/ecc"
12 )
13
14 func TestCurves(t *testing.T) {
15 for _, curve := range ecc.Curves {
16 ECDSACurve, ok := curve.Curve.(ecc.ECDSACurve)
17 if !ok {
18 continue
19 }
20
21 t.Run(ECDSACurve.GetCurveName(), func(t *testing.T) {
22 testFingerprint := make([]byte, 20)
23 _, err := io.ReadFull(rand.Reader, testFingerprint[:])
24 if err != nil {
25 t.Fatal(err)
26 }
27
28 priv := testGenerate(t, ECDSACurve)
29 testSignVerify(t, priv)
30 testValidation(t, priv)
31
32 // Needs fresh key
33 priv = testGenerate(t, ECDSACurve)
34 testMarshalUnmarshal(t, priv)
35 })
36 }
37 }
38
39 func testGenerate(t *testing.T, curve ecc.ECDSACurve) *PrivateKey {
40 priv, err := GenerateKey(rand.Reader, curve)
41 if err != nil {
42 t.Fatal(err)
43 }
44
45 return priv
46 }
47
48 func testSignVerify(t *testing.T, priv *PrivateKey) {
49 digest := make([]byte, 32)
50 _, err := io.ReadFull(rand.Reader, digest[:])
51 if err != nil {
52 t.Fatal(err)
53 }
54
55 r, s, err := Sign(rand.Reader, priv, digest)
56 if err != nil {
57 t.Errorf("error signing: %s", err)
58 }
59
60 result := Verify(&priv.PublicKey, digest, r, s)
61
62 if !result {
63 t.Error("unable to verify message")
64 }
65 }
66
67 func testValidation(t *testing.T, priv *PrivateKey) {
68 if err := Validate(priv); err != nil {
69 t.Fatalf("valid key marked as invalid: %s", err)
70 }
71
72 priv.X.Sub(priv.X, big.NewInt(1))
73 if err := Validate(priv); err == nil {
74 t.Fatal("failed to detect invalid key")
75 }
76 }
77
78 func testMarshalUnmarshal(t *testing.T, priv *PrivateKey) {
79 p := priv.MarshalPoint()
80 d := priv.MarshalIntegerSecret()
81
82 parsed := NewPrivateKey(*NewPublicKey(priv.GetCurve()))
83
84 if err := parsed.UnmarshalPoint(p); err != nil {
85 t.Fatalf("unable to unmarshal point: %s", err)
86 }
87
88 if err := parsed.UnmarshalIntegerSecret(d); err != nil {
89 t.Fatalf("unable to unmarshal integer: %s", err)
90 }
91
92 if priv.X.Cmp(parsed.X) != 0 || priv.Y.Cmp(parsed.Y) != 0 || priv.D.Cmp(parsed.D) != 0 {
93 t.Fatal("failed to marshal/unmarshal correctly")
94 }
95 }