blake3.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.blake3 = void 0;
  4. const _assert_js_1 = require("./_assert.js");
  5. const _u64_js_1 = require("./_u64.js");
  6. const _blake_js_1 = require("./_blake.js");
  7. const blake2s_js_1 = require("./blake2s.js");
  8. const utils_js_1 = require("./utils.js");
  9. const SIGMA = /* @__PURE__ */ (() => {
  10. const Id = Array.from({ length: 16 }, (_, i) => i);
  11. const permute = (arr) => [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]);
  12. const res = [];
  13. for (let i = 0, v = Id; i < 7; i++, v = permute(v))
  14. res.push(...v);
  15. return Uint8Array.from(res);
  16. })();
  17. // Why is this so slow? It should be 6x faster than blake2b.
  18. // - There is only 30% reduction in number of rounds from blake2s
  19. // - This function uses tree mode to achive parallelisation via SIMD and threading,
  20. // however in JS we don't have threads and SIMD, so we get only overhead from tree structure
  21. // - It is possible to speed it up via Web Workers, hovewer it will make code singnificantly more
  22. // complicated, which we are trying to avoid, since this library is intended to be used
  23. // for cryptographic purposes. Also, parallelization happens only on chunk level (1024 bytes),
  24. // which won't really benefit small inputs.
  25. class BLAKE3 extends _blake_js_1.BLAKE {
  26. constructor(opts = {}, flags = 0) {
  27. super(64, opts.dkLen === undefined ? 32 : opts.dkLen, {}, Number.MAX_SAFE_INTEGER, 0, 0);
  28. this.flags = 0 | 0;
  29. this.chunkPos = 0; // Position of current block in chunk
  30. this.chunksDone = 0; // How many chunks we already have
  31. this.stack = [];
  32. // Output
  33. this.posOut = 0;
  34. this.bufferOut32 = new Uint32Array(16);
  35. this.chunkOut = 0; // index of output chunk
  36. this.enableXOF = true;
  37. this.outputLen = opts.dkLen === undefined ? 32 : opts.dkLen;
  38. (0, _assert_js_1.number)(this.outputLen);
  39. if (opts.key !== undefined && opts.context !== undefined)
  40. throw new Error('Blake3: only key or context can be specified at same time');
  41. else if (opts.key !== undefined) {
  42. const key = (0, utils_js_1.toBytes)(opts.key).slice();
  43. if (key.length !== 32)
  44. throw new Error('Blake3: key should be 32 byte');
  45. this.IV = (0, utils_js_1.u32)(key);
  46. if (!utils_js_1.isLE)
  47. (0, utils_js_1.byteSwap32)(this.IV);
  48. this.flags = flags | 16 /* B3_Flags.KEYED_HASH */;
  49. }
  50. else if (opts.context !== undefined) {
  51. const context_key = new BLAKE3({ dkLen: 32 }, 32 /* B3_Flags.DERIVE_KEY_CONTEXT */)
  52. .update(opts.context)
  53. .digest();
  54. this.IV = (0, utils_js_1.u32)(context_key);
  55. if (!utils_js_1.isLE)
  56. (0, utils_js_1.byteSwap32)(this.IV);
  57. this.flags = flags | 64 /* B3_Flags.DERIVE_KEY_MATERIAL */;
  58. }
  59. else {
  60. this.IV = blake2s_js_1.B2S_IV.slice();
  61. this.flags = flags;
  62. }
  63. this.state = this.IV.slice();
  64. this.bufferOut = (0, utils_js_1.u8)(this.bufferOut32);
  65. }
  66. // Unused
  67. get() {
  68. return [];
  69. }
  70. set() { }
  71. b2Compress(counter, flags, buf, bufPos = 0) {
  72. const { state: s, pos } = this;
  73. const { h, l } = (0, _u64_js_1.fromBig)(BigInt(counter), true);
  74. // prettier-ignore
  75. const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = (0, blake2s_js_1.compress)(SIGMA, bufPos, buf, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], blake2s_js_1.B2S_IV[0], blake2s_js_1.B2S_IV[1], blake2s_js_1.B2S_IV[2], blake2s_js_1.B2S_IV[3], h, l, pos, flags);
  76. s[0] = v0 ^ v8;
  77. s[1] = v1 ^ v9;
  78. s[2] = v2 ^ v10;
  79. s[3] = v3 ^ v11;
  80. s[4] = v4 ^ v12;
  81. s[5] = v5 ^ v13;
  82. s[6] = v6 ^ v14;
  83. s[7] = v7 ^ v15;
  84. }
  85. compress(buf, bufPos = 0, isLast = false) {
  86. // Compress last block
  87. let flags = this.flags;
  88. if (!this.chunkPos)
  89. flags |= 1 /* B3_Flags.CHUNK_START */;
  90. if (this.chunkPos === 15 || isLast)
  91. flags |= 2 /* B3_Flags.CHUNK_END */;
  92. if (!isLast)
  93. this.pos = this.blockLen;
  94. this.b2Compress(this.chunksDone, flags, buf, bufPos);
  95. this.chunkPos += 1;
  96. // If current block is last in chunk (16 blocks), then compress chunks
  97. if (this.chunkPos === 16 || isLast) {
  98. let chunk = this.state;
  99. this.state = this.IV.slice();
  100. // If not the last one, compress only when there are trailing zeros in chunk counter
  101. // chunks used as binary tree where current stack is path. Zero means current leaf is finished and can be compressed.
  102. // 1 (001) - leaf not finished (just push current chunk to stack)
  103. // 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back)
  104. // 3 (011) - last leaf not finished
  105. // 4 (100) - leafs finished at depth=1 and depth=2
  106. for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) {
  107. if (!(last = this.stack.pop()))
  108. break;
  109. this.buffer32.set(last, 0);
  110. this.buffer32.set(chunk, 8);
  111. this.pos = this.blockLen;
  112. this.b2Compress(0, this.flags | 4 /* B3_Flags.PARENT */, this.buffer32, 0);
  113. chunk = this.state;
  114. this.state = this.IV.slice();
  115. }
  116. this.chunksDone++;
  117. this.chunkPos = 0;
  118. this.stack.push(chunk);
  119. }
  120. this.pos = 0;
  121. }
  122. _cloneInto(to) {
  123. to = super._cloneInto(to);
  124. const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this;
  125. to.state.set(state.slice());
  126. to.stack = stack.map((i) => Uint32Array.from(i));
  127. to.IV.set(IV);
  128. to.flags = flags;
  129. to.chunkPos = chunkPos;
  130. to.chunksDone = chunksDone;
  131. to.posOut = posOut;
  132. to.chunkOut = chunkOut;
  133. to.enableXOF = this.enableXOF;
  134. to.bufferOut32.set(this.bufferOut32);
  135. return to;
  136. }
  137. destroy() {
  138. this.destroyed = true;
  139. this.state.fill(0);
  140. this.buffer32.fill(0);
  141. this.IV.fill(0);
  142. this.bufferOut32.fill(0);
  143. for (let i of this.stack)
  144. i.fill(0);
  145. }
  146. // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8)
  147. b2CompressOut() {
  148. const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this;
  149. const { h, l } = (0, _u64_js_1.fromBig)(BigInt(this.chunkOut++));
  150. if (!utils_js_1.isLE)
  151. (0, utils_js_1.byteSwap32)(buffer32);
  152. // prettier-ignore
  153. const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = (0, blake2s_js_1.compress)(SIGMA, 0, buffer32, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], blake2s_js_1.B2S_IV[0], blake2s_js_1.B2S_IV[1], blake2s_js_1.B2S_IV[2], blake2s_js_1.B2S_IV[3], l, h, pos, flags);
  154. out32[0] = v0 ^ v8;
  155. out32[1] = v1 ^ v9;
  156. out32[2] = v2 ^ v10;
  157. out32[3] = v3 ^ v11;
  158. out32[4] = v4 ^ v12;
  159. out32[5] = v5 ^ v13;
  160. out32[6] = v6 ^ v14;
  161. out32[7] = v7 ^ v15;
  162. out32[8] = s[0] ^ v8;
  163. out32[9] = s[1] ^ v9;
  164. out32[10] = s[2] ^ v10;
  165. out32[11] = s[3] ^ v11;
  166. out32[12] = s[4] ^ v12;
  167. out32[13] = s[5] ^ v13;
  168. out32[14] = s[6] ^ v14;
  169. out32[15] = s[7] ^ v15;
  170. if (!utils_js_1.isLE) {
  171. (0, utils_js_1.byteSwap32)(buffer32);
  172. (0, utils_js_1.byteSwap32)(out32);
  173. }
  174. this.posOut = 0;
  175. }
  176. finish() {
  177. if (this.finished)
  178. return;
  179. this.finished = true;
  180. // Padding
  181. this.buffer.fill(0, this.pos);
  182. // Process last chunk
  183. let flags = this.flags | 8 /* B3_Flags.ROOT */;
  184. if (this.stack.length) {
  185. flags |= 4 /* B3_Flags.PARENT */;
  186. if (!utils_js_1.isLE)
  187. (0, utils_js_1.byteSwap32)(this.buffer32);
  188. this.compress(this.buffer32, 0, true);
  189. if (!utils_js_1.isLE)
  190. (0, utils_js_1.byteSwap32)(this.buffer32);
  191. this.chunksDone = 0;
  192. this.pos = this.blockLen;
  193. }
  194. else {
  195. flags |= (!this.chunkPos ? 1 /* B3_Flags.CHUNK_START */ : 0) | 2 /* B3_Flags.CHUNK_END */;
  196. }
  197. this.flags = flags;
  198. this.b2CompressOut();
  199. }
  200. writeInto(out) {
  201. (0, _assert_js_1.exists)(this, false);
  202. (0, _assert_js_1.bytes)(out);
  203. this.finish();
  204. const { blockLen, bufferOut } = this;
  205. for (let pos = 0, len = out.length; pos < len;) {
  206. if (this.posOut >= blockLen)
  207. this.b2CompressOut();
  208. const take = Math.min(blockLen - this.posOut, len - pos);
  209. out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
  210. this.posOut += take;
  211. pos += take;
  212. }
  213. return out;
  214. }
  215. xofInto(out) {
  216. if (!this.enableXOF)
  217. throw new Error('XOF is not possible after digest call');
  218. return this.writeInto(out);
  219. }
  220. xof(bytes) {
  221. (0, _assert_js_1.number)(bytes);
  222. return this.xofInto(new Uint8Array(bytes));
  223. }
  224. digestInto(out) {
  225. (0, _assert_js_1.output)(out, this);
  226. if (this.finished)
  227. throw new Error('digest() was already called');
  228. this.enableXOF = false;
  229. this.writeInto(out);
  230. this.destroy();
  231. return out;
  232. }
  233. digest() {
  234. return this.digestInto(new Uint8Array(this.outputLen));
  235. }
  236. }
  237. /**
  238. * BLAKE3 hash function.
  239. * @param msg - message that would be hashed
  240. * @param opts - dkLen, key, context
  241. */
  242. exports.blake3 = (0, utils_js_1.wrapXOFConstructorWithOpts)((opts) => new BLAKE3(opts));
  243. //# sourceMappingURL=blake3.js.map