From 9f4dfd1e76a5bdb2e17a92f2460fafbf8b760a8b Mon Sep 17 00:00:00 2001 From: Chris Duncan Date: Tue, 30 Jun 2026 22:45:29 -0700 Subject: [PATCH] Extract blake initialization to separate private method. --- src/lib/crypto/blake2b.ts | 54 +++++++++++++++++++++------------------ 1 file changed, 29 insertions(+), 25 deletions(-) diff --git a/src/lib/crypto/blake2b.ts b/src/lib/crypto/blake2b.ts index d4526ac..d407199 100644 --- a/src/lib/crypto/blake2b.ts +++ b/src/lib/crypto/blake2b.ts @@ -102,6 +102,32 @@ export class Blake2b { this.#G(r, 7, 3, 4, 9, 14) } + #blake2bInit (length: number, key?: Bytes, salt?: Bytes, personal?: Bytes): void { + // output length in bytes + this.#outlen = length + + // state, 'param block' + this.#parameter_block[0] = length + this.#parameter_block[1] = key?.length ?? 0 + this.#parameter_block[2] = 1 // fanout + this.#parameter_block[3] = 1 // depth + + if (salt) this.#parameter_block.set(salt, 32) + if (personal) this.#parameter_block.set(personal, 48) + + // initialize hash state + for (let i = 0; i < 8; i++) { + this.#h[i] = Blake2b.IV[i] ^ this.#parameter_view.getBigUint64(i << 3, true) + } + + // key the hash, if applicable + if (key) { + this.#blake2bUpdate(key) + // force input buffer to reset for first block of actual message + this.#c = 128 + } + } + /** * Compression function called during three phases: on keying (if applicable), * each time the input buffer is filled, and when finalizing message block. @@ -169,7 +195,7 @@ export class Blake2b { this.#b.fill(0, this.#c) // pad final block with zeros this.#blake2bCompress(true) // set final block flag and compress const data = new DataView(this.#h.buffer) - for (let i = 0; i < this.#outlen; i++) { + for (let i = 0; i < out.length; i++) { out[i] = data.getUint8(i) } } @@ -206,7 +232,7 @@ export class Blake2b { /** Message block */ #m: BigUint64Array = new BigUint64Array(16) /** User-requested output length */ - #outlen: number + #outlen: number = 64 /** * Creates a BLAKE2b hashing context. @@ -252,29 +278,7 @@ export class Blake2b { throw new RangeError(`personal must be ${B.PERSONALBYTES} bytes`) } } - - this.#outlen = length // output length in bytes - - // state, 'param block' - this.#parameter_block[0] = length - this.#parameter_block[1] = key?.length ?? 0 - this.#parameter_block[2] = 1 // fanout - this.#parameter_block[3] = 1 // depth - - if (salt) this.#parameter_block.set(salt, 32) - if (personal) this.#parameter_block.set(personal, 48) - - // initialize hash state - for (let i = 0; i < 8; i++) { - this.#h[i] = B.IV[i] ^ this.#parameter_view.getBigUint64(i << 3, true) - } - - // key the hash, if applicable - if (key) { - this.#blake2bUpdate(key) - // force input buffer to reset for first block of actual message - this.#c = 128 - } + this.#blake2bInit(length, key, salt, personal) } /** -- 2.52.0