Source file src/crypto/hmac/hmac_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 hmac_test
     5  
     6  import (
     7  	"bytes"
     8  	"crypto/hmac"
     9  	"crypto/internal/cryptotest/wycheproof"
    10  	"crypto/sha1"
    11  	"crypto/sha256"
    12  	"crypto/sha3"
    13  	"crypto/sha512"
    14  	"hash"
    15  	"testing"
    16  )
    17  
    18  func TestHMACWycheproof(t *testing.T) {
    19  	filesToHash := map[string]func() hash.Hash{
    20  		"hmac_sha1_test.json":       sha1.New,
    21  		"hmac_sha224_test.json":     sha256.New224,
    22  		"hmac_sha256_test.json":     sha256.New,
    23  		"hmac_sha3_224_test.json":   func() hash.Hash { return sha3.New224() },
    24  		"hmac_sha3_256_test.json":   func() hash.Hash { return sha3.New256() },
    25  		"hmac_sha3_384_test.json":   func() hash.Hash { return sha3.New384() },
    26  		"hmac_sha3_512_test.json":   func() hash.Hash { return sha3.New512() },
    27  		"hmac_sha384_test.json":     sha512.New384,
    28  		"hmac_sha512_test.json":     sha512.New,
    29  		"hmac_sha512_224_test.json": sha512.New512_224,
    30  		"hmac_sha512_256_test.json": sha512.New512_256,
    31  	}
    32  
    33  	for file, h := range filesToHash {
    34  		var testdata wycheproof.MacTestSchemaV1Json
    35  		wycheproof.LoadVectorFile(t, file, &testdata)
    36  
    37  		for _, tg := range testdata.TestGroups {
    38  			// Skip test groups where the tag length does not equal the
    39  			// hash length, since crypto/hmac does not support generating
    40  			// these truncated tags.
    41  			if tg.TagSize/8 != h().Size() {
    42  				continue
    43  			}
    44  
    45  			for _, tv := range tg.Tests {
    46  				t.Run(wycheproof.TestName(file, tv), func(t *testing.T) {
    47  					t.Parallel()
    48  
    49  					hm := hmac.New(h, wycheproof.MustDecodeHex(tv.Key))
    50  					hm.Write(wycheproof.MustDecodeHex(tv.Msg))
    51  					got := bytes.Equal(wycheproof.MustDecodeHex(tv.Tag), hm.Sum(nil))
    52  					want := wycheproof.ShouldPass(t, tv.Result, tv.Flags, nil)
    53  					if want != got {
    54  						t.Errorf("unexpected result")
    55  					}
    56  				})
    57  			}
    58  		}
    59  	}
    60  }
    61  

View as plain text