Source file src/crypto/internal/fips140test/cmac_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  
     5  package fipstest
     6  
     7  import (
     8  	"bytes"
     9  	"crypto/internal/cryptotest/wycheproof"
    10  	"crypto/internal/fips140/aes"
    11  	"crypto/internal/fips140/aes/gcm"
    12  	"testing"
    13  )
    14  
    15  func TestCMACWycheproof(t *testing.T) {
    16  	const file = "aes_cmac_test.json"
    17  	var testdata wycheproof.MacTestSchemaV1Json
    18  	wycheproof.LoadVectorFile(t, file, &testdata)
    19  
    20  	for _, tg := range testdata.TestGroups {
    21  		// Skip test groups with invalid AES key sizes.
    22  		// The CMAC API takes an already-constructed aes.Block,
    23  		// so invalid key sizes are rejected at AES key creation time.
    24  		switch tg.KeySize {
    25  		case 128, 192, 256:
    26  			// Valid AES key sizes.
    27  		default:
    28  			continue
    29  		}
    30  
    31  		if tg.TagSize != 128 {
    32  			continue
    33  		}
    34  
    35  		for _, tv := range tg.Tests {
    36  			t.Run(wycheproof.TestName(file, tv), func(t *testing.T) {
    37  				t.Parallel()
    38  
    39  				key := wycheproof.MustDecodeHex(tv.Key)
    40  				msg := wycheproof.MustDecodeHex(tv.Msg)
    41  				expectedTag := wycheproof.MustDecodeHex(tv.Tag)
    42  				wantPass := wycheproof.ShouldPass(t, tv.Result, tv.Flags, nil)
    43  
    44  				b, err := aes.New(key)
    45  				if err != nil {
    46  					t.Fatalf("aes.New: %v", err)
    47  				}
    48  				c := gcm.NewCMAC(b)
    49  				tag := c.MAC(msg)
    50  
    51  				if bytes.Equal(tag[:], expectedTag) {
    52  					if !wantPass {
    53  						t.Errorf("expected failure but tag matched")
    54  					}
    55  				} else {
    56  					if wantPass {
    57  						t.Errorf("tag mismatch: got %x, want %x", tag[:], expectedTag)
    58  					}
    59  				}
    60  			})
    61  		}
    62  	}
    63  }
    64  

View as plain text