This repository has been archived on 2023-05-01. You can view files and clone it, but cannot push or open issues or pull requests.
blake3/blake3.go

297 lines
7.4 KiB
Go
Raw Normal View History

2020-01-09 20:10:01 +00:00
// Package blake3 implements the BLAKE3 cryptographic hash function.
2020-01-14 05:28:18 +00:00
package blake3 // import "lukechampine.com/blake3"
2020-01-09 20:10:01 +00:00
import (
"encoding/binary"
2020-01-10 17:43:02 +00:00
"errors"
2020-01-09 20:10:01 +00:00
"hash"
2020-01-10 17:43:02 +00:00
"io"
2020-01-10 19:39:34 +00:00
"math"
"math/bits"
2020-01-09 20:10:01 +00:00
)
const (
flagChunkStart = 1 << iota
flagChunkEnd
flagParent
flagRoot
flagKeyedHash
flagDeriveKeyContext
flagDeriveKeyMaterial
2020-07-30 17:54:11 +00:00
blockSize = 64
chunkSize = 1024
2020-08-04 22:13:57 +00:00
maxSIMD = 16 // AVX-512 vectors can store 16 words
)
2020-01-09 20:10:01 +00:00
var iv = [8]uint32{
0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A,
0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19,
2020-01-09 20:10:01 +00:00
}
2020-07-30 17:54:11 +00:00
// A node represents a chunk or parent in the BLAKE3 Merkle tree.
type node struct {
2020-07-30 17:54:11 +00:00
cv [8]uint32 // chaining value from previous node
block [16]uint32
counter uint64
blockLen uint32
flags uint32
}
2020-01-12 01:09:16 +00:00
// parentNode returns a node that incorporates the chaining values of two child
// nodes.
func parentNode(left, right [8]uint32, key [8]uint32, flags uint32) node {
2020-07-30 17:54:11 +00:00
n := node{
cv: key,
2020-01-12 01:09:16 +00:00
counter: 0, // counter is reset for parents
2020-07-30 17:54:11 +00:00
blockLen: blockSize, // block is full
flags: flags | flagParent,
2020-01-09 20:10:01 +00:00
}
2020-07-30 17:54:11 +00:00
copy(n.block[:8], left[:])
copy(n.block[8:], right[:])
return n
2020-01-09 20:10:01 +00:00
}
// Hasher implements hash.Hash.
type Hasher struct {
2020-01-12 01:59:28 +00:00
key [8]uint32
flags uint32
size int // output size, for Sum
// log(n) set of Merkle subtree roots, at most one per height.
2020-08-04 22:13:57 +00:00
stack [50][8]uint32 // 2^50 * maxSIMD * chunkSize = 2^64
2020-07-30 17:54:11 +00:00
counter uint64 // number of buffers hashed; also serves as a bit vector indicating which stack elems are occupied
2020-08-04 22:13:57 +00:00
buf [maxSIMD * chunkSize]byte
2020-07-30 17:54:11 +00:00
buflen int
2020-01-12 01:59:28 +00:00
}
2020-02-02 21:40:32 +00:00
func (h *Hasher) hasSubtreeAtHeight(i int) bool {
2020-07-30 17:54:11 +00:00
return h.counter&(1<<i) != 0
2020-01-09 20:10:01 +00:00
}
2020-07-30 17:54:11 +00:00
func (h *Hasher) pushSubtree(cv [8]uint32) {
2020-01-12 01:59:28 +00:00
// seek to first open stack slot, merging subtrees as we go
2020-02-02 21:40:32 +00:00
i := 0
2020-07-30 17:54:11 +00:00
for h.hasSubtreeAtHeight(i) {
cv = chainingValue(parentNode(h.stack[i], cv, h.key, h.flags))
i++
2020-01-09 20:10:01 +00:00
}
2020-01-12 01:59:28 +00:00
h.stack[i] = cv
2020-07-30 17:54:11 +00:00
h.counter++
2020-01-09 20:10:01 +00:00
}
2020-01-12 01:09:16 +00:00
// rootNode computes the root of the Merkle tree. It does not modify the
2020-07-30 17:54:11 +00:00
// stack.
2020-01-12 01:09:16 +00:00
func (h *Hasher) rootNode() node {
2020-08-04 22:13:57 +00:00
n := compressBuffer(&h.buf, h.buflen, &h.key, h.counter*maxSIMD, h.flags)
2020-07-30 17:54:11 +00:00
for i := bits.TrailingZeros64(h.counter); i < bits.Len64(h.counter); i++ {
2020-01-12 01:59:28 +00:00
if h.hasSubtreeAtHeight(i) {
2020-07-30 17:54:11 +00:00
n = parentNode(h.stack[i], chainingValue(n), h.key, h.flags)
2020-01-12 01:59:28 +00:00
}
2020-01-10 22:17:39 +00:00
}
n.flags |= flagRoot
return n
}
2020-01-09 20:10:01 +00:00
// Write implements hash.Hash.
func (h *Hasher) Write(p []byte) (int, error) {
lenp := len(p)
for len(p) > 0 {
2020-07-30 17:54:11 +00:00
if h.buflen == len(h.buf) {
2020-08-04 22:13:57 +00:00
n := compressBuffer(&h.buf, h.buflen, &h.key, h.counter*maxSIMD, h.flags)
2020-07-30 17:54:11 +00:00
h.pushSubtree(chainingValue(n))
h.buflen = 0
2020-01-09 20:10:01 +00:00
}
2020-07-30 17:54:11 +00:00
n := copy(h.buf[h.buflen:], p)
h.buflen += n
p = p[n:]
2020-01-09 20:10:01 +00:00
}
return lenp, nil
2020-01-09 20:10:01 +00:00
}
// Sum implements hash.Hash.
2020-01-12 01:09:16 +00:00
func (h *Hasher) Sum(b []byte) (sum []byte) {
// We need to append h.Size() bytes to b. Reuse b's capacity if possible;
// otherwise, allocate a new slice.
if total := len(b) + h.Size(); cap(b) >= total {
sum = b[:total]
} else {
sum = make([]byte, total)
copy(sum, b)
}
2020-08-04 22:13:57 +00:00
// Read into the appended portion of sum. Use a low-latency-low-throughput
// path for small digests (requiring a single compression), and a
// high-latency-high-throughput path for large digests.
if dst := sum[len(b):]; len(dst) <= 64 {
var out [64]byte
wordsToBytes(compressNode(h.rootNode()), &out)
copy(dst, out[:])
} else {
h.XOF().Read(dst)
}
2020-01-12 01:09:16 +00:00
return
2020-01-09 21:25:24 +00:00
}
2020-07-30 17:54:11 +00:00
// Reset implements hash.Hash.
func (h *Hasher) Reset() {
h.counter = 0
h.buflen = 0
}
// BlockSize implements hash.Hash.
func (h *Hasher) BlockSize() int { return 64 }
// Size implements hash.Hash.
func (h *Hasher) Size() int { return h.size }
2020-01-09 21:25:24 +00:00
// XOF returns an OutputReader initialized with the current hash state.
func (h *Hasher) XOF() *OutputReader {
return &OutputReader{
2020-01-12 01:09:16 +00:00
n: h.rootNode(),
2020-01-09 21:25:24 +00:00
}
2020-01-09 20:10:01 +00:00
}
func newHasher(key [8]uint32, flags uint32, size int) *Hasher {
return &Hasher{
key: key,
flags: flags,
size: size,
}
}
// New returns a Hasher for the specified size and key. If key is nil, the hash
2020-07-30 17:54:11 +00:00
// is unkeyed. Otherwise, len(key) must be 32.
func New(size int, key []byte) *Hasher {
if key == nil {
return newHasher(iv, 0, size)
}
var keyWords [8]uint32
2020-01-13 19:27:21 +00:00
for i := range keyWords {
keyWords[i] = binary.LittleEndian.Uint32(key[i*4:])
}
return newHasher(keyWords, flagKeyedHash, size)
}
// Sum256 and Sum512 always use the same hasher state, so we can save some time
// when hashing small inputs by constructing the hasher ahead of time.
2020-07-30 17:54:11 +00:00
var defaultHasher = New(0, nil)
// Sum256 returns the unkeyed BLAKE3 hash of b, truncated to 256 bits.
2020-01-10 22:17:39 +00:00
func Sum256(b []byte) (out [32]byte) {
2020-07-30 17:54:11 +00:00
out512 := Sum512(b)
copy(out[:], out512[:])
2020-01-10 22:17:39 +00:00
return
}
// Sum512 returns the unkeyed BLAKE3 hash of b, truncated to 512 bits.
2020-01-10 22:17:39 +00:00
func Sum512(b []byte) (out [64]byte) {
2020-07-30 17:54:11 +00:00
var n node
if len(b) <= blockSize {
hashBlock(&out, b)
return
} else if len(b) <= chunkSize {
n = compressChunk(b, &iv, 0, 0)
n.flags |= flagRoot
} else {
h := *defaultHasher
h.Write(b)
n = h.rootNode()
}
wordsToBytes(compressNode(n), &out)
2020-01-10 22:17:39 +00:00
return
}
2020-01-12 01:09:16 +00:00
// DeriveKey derives a subkey from ctx and srcKey. ctx should be hardcoded,
// globally unique, and application-specific. A good format for ctx strings is:
//
// [application] [commit timestamp] [purpose]
//
// e.g.:
//
// example.com 2019-12-25 16:18:03 session tokens v1
//
// The purpose of these requirements is to ensure that an attacker cannot trick
// two different applications into using the same context string.
2020-01-10 05:46:44 +00:00
func DeriveKey(subKey []byte, ctx string, srcKey []byte) {
// construct the derivation Hasher
const derivationIVLen = 32
h := newHasher(iv, flagDeriveKeyContext, 32)
h.Write([]byte(ctx))
2020-01-13 19:27:21 +00:00
derivationIV := h.Sum(make([]byte, 0, derivationIVLen))
var ivWords [8]uint32
for i := range ivWords {
ivWords[i] = binary.LittleEndian.Uint32(derivationIV[i*4:])
}
h = newHasher(ivWords, flagDeriveKeyMaterial, 0)
2020-01-10 05:46:44 +00:00
// derive the subKey
h.Write(srcKey)
2020-01-12 01:09:16 +00:00
h.XOF().Read(subKey)
2020-01-10 05:46:44 +00:00
}
// An OutputReader produces an seekable stream of 2^64 - 1 pseudorandom output
// bytes.
type OutputReader struct {
2020-08-02 19:09:07 +00:00
n node
2020-08-04 22:13:57 +00:00
buf [maxSIMD * blockSize]byte
2020-08-02 19:09:07 +00:00
off uint64
}
// Read implements io.Reader. Callers may assume that Read returns len(p), nil
// unless the read would extend beyond the end of the stream.
func (or *OutputReader) Read(p []byte) (int, error) {
if or.off == math.MaxUint64 {
return 0, io.EOF
} else if rem := math.MaxUint64 - or.off; uint64(len(p)) > rem {
p = p[:rem]
}
lenp := len(p)
for len(p) > 0 {
2020-08-04 22:13:57 +00:00
if or.off%(maxSIMD*blockSize) == 0 {
or.n.counter = or.off / blockSize
2020-08-02 19:09:07 +00:00
compressBlocks(&or.buf, or.n)
}
2020-08-04 22:13:57 +00:00
n := copy(p, or.buf[or.off%(maxSIMD*blockSize):])
p = p[n:]
or.off += uint64(n)
}
return lenp, nil
}
// Seek implements io.Seeker.
func (or *OutputReader) Seek(offset int64, whence int) (int64, error) {
off := or.off
switch whence {
case io.SeekStart:
if offset < 0 {
return 0, errors.New("seek position cannot be negative")
}
off = uint64(offset)
case io.SeekCurrent:
if offset < 0 {
if uint64(-offset) > off {
return 0, errors.New("seek position cannot be negative")
}
off -= uint64(-offset)
} else {
off += uint64(offset)
}
case io.SeekEnd:
off = uint64(offset) - 1
default:
panic("invalid whence")
}
or.off = off
or.n.counter = uint64(off) / blockSize
2020-08-04 22:13:57 +00:00
if or.off%(maxSIMD*blockSize) != 0 {
2020-08-02 19:09:07 +00:00
compressBlocks(&or.buf, or.n)
}
// NOTE: or.off >= 2^63 will result in a negative return value.
// Nothing we can do about this.
return int64(or.off), nil
}
2020-01-09 20:10:01 +00:00
// ensure that Hasher implements hash.Hash
var _ hash.Hash = (*Hasher)(nil)