Source file src/crypto/internal/cryptotest/key.go

     1  // Copyright 2026 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  
     5  package cryptotest
     6  
     7  import (
     8  	"bytes"
     9  	"crypto"
    10  	"reflect"
    11  	"testing"
    12  )
    13  
    14  // KeyBytes returns the encoding of a key.
    15  //
    16  // It is usually a method expression like (*ecdh.PrivateKey).Bytes.
    17  type KeyBytes[K any] interface {
    18  	func(K) []byte | func(K) ([]byte, error)
    19  }
    20  
    21  // privateKey is the interface documented in crypto.PrivateKey.
    22  type privateKey interface {
    23  	Public() crypto.PublicKey
    24  	Equal(x crypto.PrivateKey) bool
    25  }
    26  
    27  // publicKey is the interface documented in crypto.PublicKey.
    28  type publicKey interface {
    29  	Equal(x crypto.PublicKey) bool
    30  }
    31  
    32  // TestPrivateKey performs a set of tests on a private key type, checking the
    33  // Equal and Public methods documented in crypto.PrivateKey, and its encoding
    34  // like [TestKeyEncoding].
    35  //
    36  // k1 and k2 must be different keys.
    37  func TestPrivateKey[K privateKey, B KeyBytes[K]](t *testing.T, k1, k2 K, newKey func([]byte) (K, error), keyBytes B) {
    38  	parsed := parseKey(t, newKey, encodeKey(t, keyBytes, k1))
    39  	t.Run("Equal", func(t *testing.T) {
    40  		testKeyEqual(t, k1, k2, parsed, func(k K, x any) bool { return k.Equal(x) })
    41  	})
    42  	t.Run("Public", func(t *testing.T) {
    43  		public := func(k K) publicKey {
    44  			t.Helper()
    45  			p, ok := k.Public().(publicKey)
    46  			if !ok {
    47  				t.Fatalf("Public returned a %T, which has no Equal method", k.Public())
    48  			}
    49  			return p
    50  		}
    51  		p1, p2, pp := public(k1), public(k2), public(parsed)
    52  		if !p1.Equal(public(k1)) {
    53  			t.Errorf("public keys of the same private key are not Equal")
    54  		}
    55  		if !p1.Equal(pp) || !pp.Equal(p1) {
    56  			t.Errorf("public key of a re-encoded private key is not Equal to the original")
    57  		}
    58  		if p1.Equal(p2) || p2.Equal(p1) {
    59  			t.Errorf("public keys of different private keys are Equal")
    60  		}
    61  		if k1.Equal(p1) {
    62  			t.Errorf("private key is Equal to its public key")
    63  		}
    64  		if p1.Equal(k1) {
    65  			t.Errorf("public key is Equal to its private key")
    66  		}
    67  		if zero := reflect.Zero(reflect.TypeOf(p1)).Interface(); k1.Equal(zero) {
    68  			t.Errorf("private key is Equal to a zero %T", zero)
    69  		}
    70  		if zero := *new(K); p1.Equal(zero) {
    71  			t.Errorf("public key is Equal to a zero %T", zero)
    72  		}
    73  	})
    74  	TestKeyEncoding(t, k1, newKey, keyBytes)
    75  }
    76  
    77  // TestPublicKey performs a set of tests on a public key type, checking the
    78  // Equal method documented in crypto.PublicKey, and its encoding like
    79  // [TestKeyEncoding].
    80  //
    81  // k1 and k2 must be different keys.
    82  func TestPublicKey[K publicKey, B KeyBytes[K]](t *testing.T, k1, k2 K, newKey func([]byte) (K, error), keyBytes B) {
    83  	parsed := parseKey(t, newKey, encodeKey(t, keyBytes, k1))
    84  	t.Run("Equal", func(t *testing.T) {
    85  		testKeyEqual(t, k1, k2, parsed, func(k K, x any) bool { return k.Equal(x) })
    86  	})
    87  	TestKeyEncoding(t, k1, newKey, keyBytes)
    88  }
    89  
    90  // testKeyEqual checks the Equal method of k1, where parsed is the result of
    91  // encoding and parsing k1, and k2 is a different key.
    92  func testKeyEqual[K any](t *testing.T, k1, k2, parsed K, equal func(k K, x any) bool) {
    93  	if !equal(k1, k1) {
    94  		t.Errorf("key is not Equal to itself")
    95  	}
    96  	if !equal(k1, parsed) || !equal(parsed, k1) {
    97  		t.Errorf("re-encoded key is not Equal to the original")
    98  	}
    99  	if equal(k1, k2) || equal(k2, k1) {
   100  		t.Errorf("different keys are Equal")
   101  	}
   102  	if equal(k1, nil) {
   103  		t.Errorf("key is Equal to nil")
   104  	}
   105  	if equal(k1, "not a key") {
   106  		t.Errorf("key is Equal to a string")
   107  	}
   108  }
   109  
   110  // TestKeyEncoding performs a set of tests on the fixed-length encoding of a key
   111  // type, checking that it round-trips, that inputs of the wrong length are
   112  // rejected, and that keys don't share memory with the input of newKey or with
   113  // the output of keyBytes.
   114  //
   115  // newKey parses the encoding and keyBytes produces it, like NewPrivateKey and
   116  // PrivateKey.Bytes in crypto/ecdh. k should come from a function other than
   117  // newKey, such as GenerateKey, so that both are tested.
   118  func TestKeyEncoding[K any, B KeyBytes[K]](t *testing.T, k K, newKey func([]byte) (K, error), keyBytes B) {
   119  	enc := bytes.Clone(encodeKey(t, keyBytes, k))
   120  
   121  	t.Run("Roundtrip", func(t *testing.T) {
   122  		in := bytes.Clone(enc)
   123  		parsed := parseKey(t, newKey, in)
   124  		if !bytes.Equal(in, enc) {
   125  			t.Errorf("newKey modified its input")
   126  		}
   127  		if got := encodeKey(t, keyBytes, parsed); !bytes.Equal(got, enc) {
   128  			t.Errorf("re-encoded key mismatch: got %x, want %x", got, enc)
   129  		}
   130  	})
   131  
   132  	t.Run("WrongLength", func(t *testing.T) {
   133  		for _, in := range [][]byte{
   134  			nil, {}, enc[:len(enc)-1], enc[:len(enc)/2],
   135  			append(bytes.Clone(enc), 0), append([]byte{0}, enc...),
   136  			append(bytes.Clone(enc), enc...),
   137  		} {
   138  			if _, err := newKey(in); err == nil {
   139  				t.Errorf("newKey accepted an input of length %d instead of %d", len(in), len(enc))
   140  			}
   141  		}
   142  	})
   143  
   144  	t.Run("InputNotRetained", func(t *testing.T) {
   145  		in := bytes.Clone(enc)
   146  		parsed := parseKey(t, newKey, in)
   147  		scribble(in)
   148  		if got := encodeKey(t, keyBytes, parsed); !bytes.Equal(got, enc) {
   149  			t.Errorf("modifying the input of newKey changed the key")
   150  		}
   151  	})
   152  
   153  	t.Run("OutputNotAliased", func(t *testing.T) {
   154  		outputNotAliased := func(t *testing.T, k K) {
   155  			b1, b2 := encodeKey(t, keyBytes, k), encodeKey(t, keyBytes, k)
   156  			scribble(b1)
   157  			if !bytes.Equal(b2, enc) {
   158  				t.Errorf("modifying the output of keyBytes changed another output")
   159  			}
   160  			if got := encodeKey(t, keyBytes, k); !bytes.Equal(got, enc) {
   161  				t.Errorf("modifying the output of keyBytes changed the key")
   162  			}
   163  		}
   164  		t.Run("Parsed", func(t *testing.T) {
   165  			outputNotAliased(t, parseKey(t, newKey, bytes.Clone(enc)))
   166  		})
   167  		// This runs last because a failure leaves k modified.
   168  		t.Run("Original", func(t *testing.T) {
   169  			outputNotAliased(t, k)
   170  		})
   171  	})
   172  }
   173  
   174  func parseKey[K any](t *testing.T, newKey func([]byte) (K, error), in []byte) K {
   175  	t.Helper()
   176  	k, err := newKey(in)
   177  	if err != nil {
   178  		t.Fatal(err)
   179  	}
   180  	return k
   181  }
   182  
   183  func encodeKey[K any, B KeyBytes[K]](t *testing.T, keyBytes B, k K) []byte {
   184  	t.Helper()
   185  	switch keyBytes := any(keyBytes).(type) {
   186  	case func(K) []byte:
   187  		return keyBytes(k)
   188  	case func(K) ([]byte, error):
   189  		b, err := keyBytes(k)
   190  		if err != nil {
   191  			t.Fatal(err)
   192  		}
   193  		return b
   194  	default:
   195  		panic("unreachable")
   196  	}
   197  }
   198  
   199  // scribble changes every byte of b, including its spare capacity, which a
   200  // caller could write to with append. Scribbling twice doesn't restore b.
   201  func scribble(b []byte) {
   202  	b = b[:cap(b)]
   203  	for i := range b {
   204  		b[i]++
   205  	}
   206  }
   207  

View as plain text