paulmillr / noble-hashes

Audited & minimal JS implementation of hash functions, MACs and KDFs.
https://paulmillr.com/noble
MIT License
573 stars 46 forks source link

blake3 keyed hash blanks out the key uint8array #50

Closed libitx closed 1 year ago

libitx commented 1 year ago

Unsure if this is intended - feels like a bug. When using blake3 in keyed hash mode, the key uint8array is blanked out. Eg:

const key = new Uint8Array([1,2,3,4,5,6,7,8,9... etc])
const hash = blake3(input, { key })
console.log(key) // => Uint8Array(32) [0,0,0,0,0,0,0,0,0... etc]

I currently work round this by copying the key each time I use it:

const hash = blake3(input, { key: new Uint8Array(key) })
paulmillr commented 1 year ago

Inputs must be read-only. If they're mutated, it's a bug.

libitx commented 1 year ago

Just double checked - version 1.3.0 - definitely the Blake3Opts.key gets mutated as described. Also checked Blake3Opts.context which does not get mutated.

libitx commented 1 year ago

I see what's going on. In the destroy() method this.IV gets filled with zeros. In the constructor key should be copied to prevent it being zeroed out.

https://github.com/paulmillr/noble-hashes/blob/main/src/blake3.ts#L59-L75

Eg line 62: const key = toBytes(opts.key).slice()

I can do a PR if that would be helpful?

paulmillr commented 1 year ago

Yes please.

If you could do a quick check of other places where toBytes is used, that would be very helpful.