add derive key mode
This commit is contained in:
parent
0a863bb651
commit
bd08550d6e
15
blake3.go
15
blake3.go
|
@ -263,8 +263,8 @@ func newHasher(key [8]uint32, flags uint32, out_size int) *Hasher {
|
|||
}
|
||||
}
|
||||
|
||||
// New returns a Hasher for the regular hash function.
|
||||
// If key is nil, the hash is unkeyed.
|
||||
// New returns a Hasher for the specified size and key. If key is nil, the hash
|
||||
// is unkeyed.
|
||||
func New(size int, key []byte) *Hasher {
|
||||
if key == nil {
|
||||
return newHasher(IV, 0, size)
|
||||
|
@ -274,6 +274,17 @@ func New(size int, key []byte) *Hasher {
|
|||
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) {
|
||||
h.cv_stack[h.cv_stack_len] = cv
|
||||
h.cv_stack_len++
|
||||
|
|
|
@ -45,18 +45,26 @@ func TestVectors(t *testing.T) {
|
|||
}
|
||||
|
||||
for _, vec := range vectors.Cases {
|
||||
in := input[:vec.InputLen]
|
||||
// regular
|
||||
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 {
|
||||
t.Errorf("output did not match test vector:\n\texpected: %v...\n\t got: %v...", vec.Hash[:10], out[:10])
|
||||
}
|
||||
// keyed
|
||||
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 {
|
||||
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])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Reference in New Issue