Source file src/crypto/hkdf/hkdf_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 hkdf_test
     5  
     6  import (
     7  	"bytes"
     8  	"crypto/hkdf"
     9  	"crypto/internal/cryptotest/wycheproof"
    10  	"crypto/sha1"
    11  	"crypto/sha256"
    12  	"crypto/sha512"
    13  	"hash"
    14  	"testing"
    15  )
    16  
    17  func TestHKDFWycheproof(t *testing.T) {
    18  	filesToHash := map[string]func() hash.Hash{
    19  		"hkdf_sha1_test.json":   sha1.New,
    20  		"hkdf_sha256_test.json": sha256.New,
    21  		"hkdf_sha384_test.json": sha512.New384,
    22  		"hkdf_sha512_test.json": sha512.New,
    23  	}
    24  
    25  	for file, h := range filesToHash {
    26  		var testdata wycheproof.HkdfTestSchemaV1Json
    27  		wycheproof.LoadVectorFile(t, file, &testdata)
    28  
    29  		for _, tg := range testdata.TestGroups {
    30  			for _, tv := range tg.Tests {
    31  				t.Run(wycheproof.TestName(file, tv), func(t *testing.T) {
    32  					t.Parallel()
    33  
    34  					ikm := wycheproof.MustDecodeHex(tv.Ikm)
    35  					salt := wycheproof.MustDecodeHex(tv.Salt)
    36  					info := string(wycheproof.MustDecodeHex(tv.Info))
    37  					wantPass := wycheproof.ShouldPass(t, tv.Result, tv.Flags, nil)
    38  
    39  					okm, err := hkdf.Key(h, ikm, salt, info, tv.Size)
    40  					if !wantPass {
    41  						if err == nil {
    42  							t.Errorf("Key succeeded for invalid vector")
    43  						}
    44  						return
    45  					}
    46  					if err != nil {
    47  						t.Fatalf("Key: %v", err)
    48  					}
    49  					if expectedOkm := wycheproof.MustDecodeHex(tv.Okm); !bytes.Equal(okm, expectedOkm) {
    50  						t.Errorf("output key mismatch: got %x, want %x", okm, expectedOkm)
    51  					}
    52  				})
    53  			}
    54  		}
    55  	}
    56  }
    57  

View as plain text