add derive key mode

This commit is contained in:
lukechampine 2020-01-09 15:38:44 -05:00
parent 0a863bb651
commit bd08550d6e
2 changed files with 23 additions and 4 deletions

View File

@ -263,8 +263,8 @@ func newHasher(key [8]uint32, flags uint32, out_size int) *Hasher {
} }
} }
// New returns a Hasher for the regular hash function. // New returns a Hasher for the specified size and key. If key is nil, the hash
// If key is nil, the hash is unkeyed. // is unkeyed.
func New(size int, key []byte) *Hasher { func New(size int, key []byte) *Hasher {
if key == nil { if key == nil {
return newHasher(IV, 0, size) return newHasher(IV, 0, size)
@ -274,6 +274,17 @@ func New(size int, key []byte) *Hasher {
return newHasher(key_words, KEYED_HASH, size) return newHasher(key_words, KEYED_HASH, size)
} }
// NewFromDerivedKey returns a Hasher whose key was derived from the supplied
// context string.
func NewFromDerivedKey(size int, ctx string) *Hasher {
h := newHasher(IV, DERIVE_KEY_CONTEXT, KEY_LEN)
h.Write([]byte(ctx))
key := h.Sum(nil)
var key_words [8]uint32
words_from_litte_endian_bytes(key, key_words[:])
return newHasher(key_words, DERIVE_KEY_MATERIAL, size)
}
func (h *Hasher) push_stack(cv [8]uint32) { func (h *Hasher) push_stack(cv [8]uint32) {
h.cv_stack[h.cv_stack_len] = cv h.cv_stack[h.cv_stack_len] = cv
h.cv_stack_len++ h.cv_stack_len++

View File

@ -45,18 +45,26 @@ func TestVectors(t *testing.T) {
} }
for _, vec := range vectors.Cases { for _, vec := range vectors.Cases {
in := input[:vec.InputLen]
// regular // regular
h := blake3.New(len(vec.Hash)/2, nil) h := blake3.New(len(vec.Hash)/2, nil)
h.Write(input[:vec.InputLen]) h.Write(in)
if out := toHex(h.Sum(nil)); out != vec.Hash { if out := toHex(h.Sum(nil)); out != vec.Hash {
t.Errorf("output did not match test vector:\n\texpected: %v...\n\t got: %v...", vec.Hash[:10], out[:10]) t.Errorf("output did not match test vector:\n\texpected: %v...\n\t got: %v...", vec.Hash[:10], out[:10])
} }
// keyed // keyed
h = blake3.New(len(vec.KeyedHash)/2, []byte(vectors.Key)) h = blake3.New(len(vec.KeyedHash)/2, []byte(vectors.Key))
h.Write(input[:vec.InputLen]) h.Write(in)
if out := toHex(h.Sum(nil)); out != vec.KeyedHash { if out := toHex(h.Sum(nil)); out != vec.KeyedHash {
t.Errorf("output did not match test vector:\n\texpected: %v...\n\t got: %v...", vec.KeyedHash[:10], out[:10]) t.Errorf("output did not match test vector:\n\texpected: %v...\n\t got: %v...", vec.KeyedHash[:10], out[:10])
} }
// derive key
const ctx = "BLAKE3 2019-12-27 16:29:52 test vectors context"
h = blake3.NewFromDerivedKey(len(vec.DeriveKey)/2, ctx)
h.Write(in)
if out := toHex(h.Sum(nil)); out != vec.DeriveKey {
t.Errorf("output did not match test vector:\n\texpected: %v...\n\t got: %v...", vec.DeriveKey[:10], out[:10])
}
} }
} }