github.com/hashicorp/vault/sdk@v0.11.0/helper/kdf/kdf_test.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package kdf
     5  
     6  import (
     7  	"bytes"
     8  	"testing"
     9  )
    10  
    11  func TestCounterMode(t *testing.T) {
    12  	key := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
    13  	context := []byte("the quick brown fox")
    14  	prf := HMACSHA256PRF
    15  	prfLen := HMACSHA256PRFLen
    16  
    17  	// Expect256 was generated in python with
    18  	// import hashlib, hmac
    19  	// hash = hashlib.sha256
    20  	// context = "the quick brown fox"
    21  	// key = "".join([chr(x) for x in range(1, 17)])
    22  	// inp = "\x00\x00\x00\x00"+context+"\x00\x00\x01\x00"
    23  	// digest = hmac.HMAC(key, inp, hash).digest()
    24  	// print [ord(x) for x in digest]
    25  	expect256 := []byte{
    26  		219, 25, 238, 6, 185, 236, 180, 64, 248, 152, 251,
    27  		153, 79, 5, 141, 222, 66, 200, 66, 143, 40, 3, 101, 221, 206, 163, 102,
    28  		80, 88, 234, 87, 157,
    29  	}
    30  
    31  	for _, l := range []uint32{128, 256, 384, 1024} {
    32  		out, err := CounterMode(prf, prfLen, key, context, l)
    33  		if err != nil {
    34  			t.Fatalf("err: %v", err)
    35  		}
    36  
    37  		if uint32(len(out)*8) != l {
    38  			t.Fatalf("bad length: %#v", out)
    39  		}
    40  
    41  		if bytes.Contains(out, key) {
    42  			t.Fatalf("output contains key")
    43  		}
    44  
    45  		if l == 256 && !bytes.Equal(out, expect256) {
    46  			t.Fatalf("mis-match")
    47  		}
    48  	}
    49  }
    50  
    51  func TestHMACSHA256PRF(t *testing.T) {
    52  	key := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
    53  	data := []byte("foobarbaz")
    54  	out, err := HMACSHA256PRF(key, data)
    55  	if err != nil {
    56  		t.Fatalf("err: %v", err)
    57  	}
    58  
    59  	if uint32(len(out)*8) != HMACSHA256PRFLen {
    60  		t.Fatalf("Bad len")
    61  	}
    62  
    63  	// Expect was generated in python with:
    64  	// import hashlib, hmac
    65  	// hash = hashlib.sha256
    66  	// msg = "foobarbaz"
    67  	// key = "".join([chr(x) for x in range(1, 17)])
    68  	// hm = hmac.HMAC(key, msg, hash)
    69  	// print [ord(x) for x in hm.digest()]
    70  	expect := []byte{
    71  		9, 50, 146, 8, 188, 130, 150, 107, 205, 147, 82, 170,
    72  		253, 183, 26, 38, 167, 194, 220, 111, 56, 118, 219, 209, 31, 52, 137,
    73  		90, 246, 133, 191, 124,
    74  	}
    75  	if !bytes.Equal(expect, out) {
    76  		t.Fatalf("mis-matched output")
    77  	}
    78  }