1// Copyright 2020 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package ecdsa_test
6
7import (
8	"crypto"
9	"crypto/ecdsa"
10	"crypto/elliptic"
11	"crypto/rand"
12	"crypto/x509"
13	"testing"
14)
15
16func testEqual(t *testing.T, c elliptic.Curve) {
17	private, _ := ecdsa.GenerateKey(c, rand.Reader)
18	public := &private.PublicKey
19
20	if !public.Equal(public) {
21		t.Errorf("public key is not equal to itself: %v", public)
22	}
23	if !public.Equal(crypto.Signer(private).Public().(*ecdsa.PublicKey)) {
24		t.Errorf("private.Public() is not Equal to public: %q", public)
25	}
26	if !private.Equal(private) {
27		t.Errorf("private key is not equal to itself: %v", private)
28	}
29
30	enc, err := x509.MarshalPKCS8PrivateKey(private)
31	if err != nil {
32		t.Fatal(err)
33	}
34	decoded, err := x509.ParsePKCS8PrivateKey(enc)
35	if err != nil {
36		t.Fatal(err)
37	}
38	if !public.Equal(decoded.(crypto.Signer).Public()) {
39		t.Errorf("public key is not equal to itself after decoding: %v", public)
40	}
41	if !private.Equal(decoded) {
42		t.Errorf("private key is not equal to itself after decoding: %v", private)
43	}
44
45	other, _ := ecdsa.GenerateKey(c, rand.Reader)
46	if public.Equal(other.Public()) {
47		t.Errorf("different public keys are Equal")
48	}
49	if private.Equal(other) {
50		t.Errorf("different private keys are Equal")
51	}
52
53	// Ensure that keys with the same coordinates but on different curves
54	// aren't considered Equal.
55	differentCurve := &ecdsa.PublicKey{}
56	*differentCurve = *public // make a copy of the public key
57	if differentCurve.Curve == elliptic.P256() {
58		differentCurve.Curve = elliptic.P224()
59	} else {
60		differentCurve.Curve = elliptic.P256()
61	}
62	if public.Equal(differentCurve) {
63		t.Errorf("public keys with different curves are Equal")
64	}
65}
66
67func TestEqual(t *testing.T) {
68	t.Run("P224", func(t *testing.T) { testEqual(t, elliptic.P224()) })
69	if testing.Short() {
70		return
71	}
72	t.Run("P256", func(t *testing.T) { testEqual(t, elliptic.P256()) })
73	t.Run("P384", func(t *testing.T) { testEqual(t, elliptic.P384()) })
74	t.Run("P521", func(t *testing.T) { testEqual(t, elliptic.P521()) })
75}
76