Source file src/crypto/ecdsa/ecdsa_wycheproof_test.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  package ecdsa_test
     5  
     6  import (
     7  	"crypto/ecdsa"
     8  	"crypto/internal/cryptotest/wycheproof"
     9  	"crypto/x509"
    10  	"fmt"
    11  	"testing"
    12  )
    13  
    14  func TestECDSAWycheproof(t *testing.T) {
    15  	// A map of supported curves to the list of hashes that Wycheproof has
    16  	// test vector coverage for.
    17  	curveAndHashes := map[string][]string{
    18  		"secp224r1": {
    19  			"sha224",
    20  			"sha256",
    21  			"sha512",
    22  			"sha3_224",
    23  			"sha3_256",
    24  			"sha3_512",
    25  		},
    26  		"secp256r1": {
    27  			"sha256",
    28  			"sha512",
    29  			"sha3_256",
    30  			"sha3_512",
    31  		},
    32  		"secp384r1": {
    33  			"sha256",
    34  			"sha384",
    35  			"sha512",
    36  			"sha3_384",
    37  			"sha3_512",
    38  		},
    39  		"secp521r1": {
    40  			"sha512",
    41  			"sha3_512",
    42  		},
    43  	}
    44  
    45  	var files []string
    46  	for c, hashes := range curveAndHashes {
    47  		for _, h := range hashes {
    48  			files = append(files, fmt.Sprintf("ecdsa_%s_%s_test.json", c, h))
    49  		}
    50  	}
    51  
    52  	parseSPKIPub := func(p []byte) (*ecdsa.PublicKey, error) {
    53  		pubKeyAny, err := x509.ParsePKIXPublicKey(p)
    54  		if err != nil {
    55  			return nil, err
    56  		}
    57  		ecdsaPub, ok := pubKeyAny.(*ecdsa.PublicKey)
    58  		if !ok {
    59  			return nil, fmt.Errorf("unexpected key type %T", pubKeyAny)
    60  		}
    61  		return ecdsaPub, nil
    62  	}
    63  
    64  	for _, file := range files {
    65  		var testdata wycheproof.EcdsaVerifySchemaV1Json
    66  		wycheproof.LoadVectorFile(t, file, &testdata)
    67  
    68  		for tgIdx, tg := range testdata.TestGroups {
    69  			pubkey, err := parseSPKIPub(wycheproof.MustDecodeHex(tg.PublicKeyDer))
    70  			if err != nil {
    71  				t.Fatalf("test group %d invalid DER encoded public key: %v", tgIdx+1, err)
    72  			}
    73  
    74  			h := wycheproof.ParseHash(tg.Sha)
    75  
    76  			for _, tv := range tg.Tests {
    77  				t.Run(wycheproof.TestName(file, tv), func(t *testing.T) {
    78  					t.Parallel()
    79  
    80  					h := h.New()
    81  					h.Write(wycheproof.MustDecodeHex(tv.Msg))
    82  					got := ecdsa.VerifyASN1(pubkey, h.Sum(nil), wycheproof.MustDecodeHex(tv.Sig))
    83  
    84  					if want := wycheproof.ShouldPass(t, tv.Result, tv.Flags, nil); got != want {
    85  						t.Errorf("VerifyASN1 wanted success: %t", want)
    86  					}
    87  				})
    88  			}
    89  		}
    90  	}
    91  }
    92  

View as plain text