sha3-addons.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.keccakprg = exports.KeccakPRG = exports.m14 = exports.k12 = exports.KangarooTwelve = exports.turboshake256 = exports.turboshake128 = exports.parallelhash256xof = exports.parallelhash128xof = exports.parallelhash256 = exports.parallelhash128 = exports.ParallelHash = exports.tuplehash256xof = exports.tuplehash128xof = exports.tuplehash256 = exports.tuplehash128 = exports.TupleHash = exports.kmac256xof = exports.kmac128xof = exports.kmac256 = exports.kmac128 = exports.KMAC = exports.cshake256 = exports.cshake128 = void 0;
  4. /**
  5. * SHA3 (keccak) addons.
  6. *
  7. * * Full [NIST SP 800-185](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf):
  8. * cSHAKE, KMAC, TupleHash, ParallelHash + XOF variants
  9. * * Reduced-round Keccak [(draft)](https://datatracker.ietf.org/doc/draft-irtf-cfrg-kangarootwelve/):
  10. * * 🦘 K12 aka KangarooTwelve
  11. * * M14 aka MarsupilamiFourteen
  12. * * TurboSHAKE
  13. * * KeccakPRG: Pseudo-random generator based on Keccak [(pdf)](https://keccak.team/files/CSF-0.1.pdf)
  14. * @module
  15. */
  16. const sha3_ts_1 = require("./sha3.js");
  17. const utils_ts_1 = require("./utils.js");
  18. // cSHAKE && KMAC (NIST SP800-185)
  19. const _8n = BigInt(8);
  20. const _ffn = BigInt(0xff);
  21. // NOTE: it is safe to use bigints here, since they used only for length encoding (not actual data).
  22. // We use bigints in sha256 for lengths too.
  23. function leftEncode(n) {
  24. n = BigInt(n);
  25. const res = [Number(n & _ffn)];
  26. n >>= _8n;
  27. for (; n > 0; n >>= _8n)
  28. res.unshift(Number(n & _ffn));
  29. res.unshift(res.length);
  30. return new Uint8Array(res);
  31. }
  32. function rightEncode(n) {
  33. n = BigInt(n);
  34. const res = [Number(n & _ffn)];
  35. n >>= _8n;
  36. for (; n > 0; n >>= _8n)
  37. res.unshift(Number(n & _ffn));
  38. res.push(res.length);
  39. return new Uint8Array(res);
  40. }
  41. function chooseLen(opts, outputLen) {
  42. return opts.dkLen === undefined ? outputLen : opts.dkLen;
  43. }
  44. const abytesOrZero = (buf) => {
  45. if (buf === undefined)
  46. return Uint8Array.of();
  47. return (0, utils_ts_1.toBytes)(buf);
  48. };
  49. // NOTE: second modulo is necessary since we don't need to add padding if current element takes whole block
  50. const getPadding = (len, block) => new Uint8Array((block - (len % block)) % block);
  51. // Personalization
  52. function cshakePers(hash, opts = {}) {
  53. if (!opts || (!opts.personalization && !opts.NISTfn))
  54. return hash;
  55. // Encode and pad inplace to avoid unneccesary memory copies/slices (so we don't need to zero them later)
  56. // bytepad(encode_string(N) || encode_string(S), 168)
  57. const blockLenBytes = leftEncode(hash.blockLen);
  58. const fn = abytesOrZero(opts.NISTfn);
  59. const fnLen = leftEncode(_8n * BigInt(fn.length)); // length in bits
  60. const pers = abytesOrZero(opts.personalization);
  61. const persLen = leftEncode(_8n * BigInt(pers.length)); // length in bits
  62. if (!fn.length && !pers.length)
  63. return hash;
  64. hash.suffix = 0x04;
  65. hash.update(blockLenBytes).update(fnLen).update(fn).update(persLen).update(pers);
  66. let totalLen = blockLenBytes.length + fnLen.length + fn.length + persLen.length + pers.length;
  67. hash.update(getPadding(totalLen, hash.blockLen));
  68. return hash;
  69. }
  70. const gencShake = (suffix, blockLen, outputLen) => (0, utils_ts_1.createXOFer)((opts = {}) => cshakePers(new sha3_ts_1.Keccak(blockLen, suffix, chooseLen(opts, outputLen), true), opts));
  71. exports.cshake128 = (() => gencShake(0x1f, 168, 128 / 8))();
  72. exports.cshake256 = (() => gencShake(0x1f, 136, 256 / 8))();
  73. class KMAC extends sha3_ts_1.Keccak {
  74. constructor(blockLen, outputLen, enableXOF, key, opts = {}) {
  75. super(blockLen, 0x1f, outputLen, enableXOF);
  76. cshakePers(this, { NISTfn: 'KMAC', personalization: opts.personalization });
  77. key = (0, utils_ts_1.toBytes)(key);
  78. (0, utils_ts_1.abytes)(key);
  79. // 1. newX = bytepad(encode_string(K), 168) || X || right_encode(L).
  80. const blockLenBytes = leftEncode(this.blockLen);
  81. const keyLen = leftEncode(_8n * BigInt(key.length));
  82. this.update(blockLenBytes).update(keyLen).update(key);
  83. const totalLen = blockLenBytes.length + keyLen.length + key.length;
  84. this.update(getPadding(totalLen, this.blockLen));
  85. }
  86. finish() {
  87. if (!this.finished)
  88. this.update(rightEncode(this.enableXOF ? 0 : _8n * BigInt(this.outputLen))); // outputLen in bits
  89. super.finish();
  90. }
  91. _cloneInto(to) {
  92. // Create new instance without calling constructor since key already in state and we don't know it.
  93. // Force "to" to be instance of KMAC instead of Sha3.
  94. if (!to) {
  95. to = Object.create(Object.getPrototypeOf(this), {});
  96. to.state = this.state.slice();
  97. to.blockLen = this.blockLen;
  98. to.state32 = (0, utils_ts_1.u32)(to.state);
  99. }
  100. return super._cloneInto(to);
  101. }
  102. clone() {
  103. return this._cloneInto();
  104. }
  105. }
  106. exports.KMAC = KMAC;
  107. function genKmac(blockLen, outputLen, xof = false) {
  108. const kmac = (key, message, opts) => kmac.create(key, opts).update(message).digest();
  109. kmac.create = (key, opts = {}) => new KMAC(blockLen, chooseLen(opts, outputLen), xof, key, opts);
  110. return kmac;
  111. }
  112. exports.kmac128 = (() => genKmac(168, 128 / 8))();
  113. exports.kmac256 = (() => genKmac(136, 256 / 8))();
  114. exports.kmac128xof = (() => genKmac(168, 128 / 8, true))();
  115. exports.kmac256xof = (() => genKmac(136, 256 / 8, true))();
  116. // TupleHash
  117. // Usage: tuple(['ab', 'cd']) != tuple(['a', 'bcd'])
  118. class TupleHash extends sha3_ts_1.Keccak {
  119. constructor(blockLen, outputLen, enableXOF, opts = {}) {
  120. super(blockLen, 0x1f, outputLen, enableXOF);
  121. cshakePers(this, { NISTfn: 'TupleHash', personalization: opts.personalization });
  122. // Change update after cshake processed
  123. this.update = (data) => {
  124. data = (0, utils_ts_1.toBytes)(data);
  125. (0, utils_ts_1.abytes)(data);
  126. super.update(leftEncode(_8n * BigInt(data.length)));
  127. super.update(data);
  128. return this;
  129. };
  130. }
  131. finish() {
  132. if (!this.finished)
  133. super.update(rightEncode(this.enableXOF ? 0 : _8n * BigInt(this.outputLen))); // outputLen in bits
  134. super.finish();
  135. }
  136. _cloneInto(to) {
  137. to || (to = new TupleHash(this.blockLen, this.outputLen, this.enableXOF));
  138. return super._cloneInto(to);
  139. }
  140. clone() {
  141. return this._cloneInto();
  142. }
  143. }
  144. exports.TupleHash = TupleHash;
  145. function genTuple(blockLen, outputLen, xof = false) {
  146. const tuple = (messages, opts) => {
  147. const h = tuple.create(opts);
  148. for (const msg of messages)
  149. h.update(msg);
  150. return h.digest();
  151. };
  152. tuple.create = (opts = {}) => new TupleHash(blockLen, chooseLen(opts, outputLen), xof, opts);
  153. return tuple;
  154. }
  155. /** 128-bit TupleHASH. */
  156. exports.tuplehash128 = (() => genTuple(168, 128 / 8))();
  157. /** 256-bit TupleHASH. */
  158. exports.tuplehash256 = (() => genTuple(136, 256 / 8))();
  159. /** 128-bit TupleHASH XOF. */
  160. exports.tuplehash128xof = (() => genTuple(168, 128 / 8, true))();
  161. /** 256-bit TupleHASH XOF. */
  162. exports.tuplehash256xof = (() => genTuple(136, 256 / 8, true))();
  163. class ParallelHash extends sha3_ts_1.Keccak {
  164. constructor(blockLen, outputLen, leafCons, enableXOF, opts = {}) {
  165. super(blockLen, 0x1f, outputLen, enableXOF);
  166. this.chunkPos = 0; // Position of current block in chunk
  167. this.chunksDone = 0; // How many chunks we already have
  168. cshakePers(this, { NISTfn: 'ParallelHash', personalization: opts.personalization });
  169. this.leafCons = leafCons;
  170. let { blockLen: B } = opts;
  171. B || (B = 8);
  172. (0, utils_ts_1.anumber)(B);
  173. this.chunkLen = B;
  174. super.update(leftEncode(B));
  175. // Change update after cshake processed
  176. this.update = (data) => {
  177. data = (0, utils_ts_1.toBytes)(data);
  178. (0, utils_ts_1.abytes)(data);
  179. const { chunkLen, leafCons } = this;
  180. for (let pos = 0, len = data.length; pos < len;) {
  181. if (this.chunkPos == chunkLen || !this.leafHash) {
  182. if (this.leafHash) {
  183. super.update(this.leafHash.digest());
  184. this.chunksDone++;
  185. }
  186. this.leafHash = leafCons();
  187. this.chunkPos = 0;
  188. }
  189. const take = Math.min(chunkLen - this.chunkPos, len - pos);
  190. this.leafHash.update(data.subarray(pos, pos + take));
  191. this.chunkPos += take;
  192. pos += take;
  193. }
  194. return this;
  195. };
  196. }
  197. finish() {
  198. if (this.finished)
  199. return;
  200. if (this.leafHash) {
  201. super.update(this.leafHash.digest());
  202. this.chunksDone++;
  203. }
  204. super.update(rightEncode(this.chunksDone));
  205. super.update(rightEncode(this.enableXOF ? 0 : _8n * BigInt(this.outputLen))); // outputLen in bits
  206. super.finish();
  207. }
  208. _cloneInto(to) {
  209. to || (to = new ParallelHash(this.blockLen, this.outputLen, this.leafCons, this.enableXOF));
  210. if (this.leafHash)
  211. to.leafHash = this.leafHash._cloneInto(to.leafHash);
  212. to.chunkPos = this.chunkPos;
  213. to.chunkLen = this.chunkLen;
  214. to.chunksDone = this.chunksDone;
  215. return super._cloneInto(to);
  216. }
  217. destroy() {
  218. super.destroy.call(this);
  219. if (this.leafHash)
  220. this.leafHash.destroy();
  221. }
  222. clone() {
  223. return this._cloneInto();
  224. }
  225. }
  226. exports.ParallelHash = ParallelHash;
  227. function genPrl(blockLen, outputLen, leaf, xof = false) {
  228. const parallel = (message, opts) => parallel.create(opts).update(message).digest();
  229. parallel.create = (opts = {}) => new ParallelHash(blockLen, chooseLen(opts, outputLen), () => leaf.create({ dkLen: 2 * outputLen }), xof, opts);
  230. return parallel;
  231. }
  232. /** 128-bit ParallelHash. In JS, it is not parallel. */
  233. exports.parallelhash128 = (() => genPrl(168, 128 / 8, exports.cshake128))();
  234. /** 256-bit ParallelHash. In JS, it is not parallel. */
  235. exports.parallelhash256 = (() => genPrl(136, 256 / 8, exports.cshake256))();
  236. /** 128-bit ParallelHash XOF. In JS, it is not parallel. */
  237. exports.parallelhash128xof = (() => genPrl(168, 128 / 8, exports.cshake128, true))();
  238. /** 256-bit ParallelHash. In JS, it is not parallel. */
  239. exports.parallelhash256xof = (() => genPrl(136, 256 / 8, exports.cshake256, true))();
  240. const genTurboshake = (blockLen, outputLen) => (0, utils_ts_1.createXOFer)((opts = {}) => {
  241. const D = opts.D === undefined ? 0x1f : opts.D;
  242. // Section 2.1 of https://datatracker.ietf.org/doc/draft-irtf-cfrg-kangarootwelve/
  243. if (!Number.isSafeInteger(D) || D < 0x01 || D > 0x7f)
  244. throw new Error('invalid domain separation byte must be 0x01..0x7f, got: ' + D);
  245. return new sha3_ts_1.Keccak(blockLen, D, opts.dkLen === undefined ? outputLen : opts.dkLen, true, 12);
  246. });
  247. /** TurboSHAKE 128-bit: reduced 12-round keccak. */
  248. exports.turboshake128 = genTurboshake(168, 256 / 8);
  249. /** TurboSHAKE 256-bit: reduced 12-round keccak. */
  250. exports.turboshake256 = genTurboshake(136, 512 / 8);
  251. // Kangaroo
  252. // Same as NIST rightEncode, but returns [0] for zero string
  253. function rightEncodeK12(n) {
  254. n = BigInt(n);
  255. const res = [];
  256. for (; n > 0; n >>= _8n)
  257. res.unshift(Number(n & _ffn));
  258. res.push(res.length);
  259. return Uint8Array.from(res);
  260. }
  261. const EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();
  262. class KangarooTwelve extends sha3_ts_1.Keccak {
  263. constructor(blockLen, leafLen, outputLen, rounds, opts) {
  264. super(blockLen, 0x07, outputLen, true, rounds);
  265. this.chunkLen = 8192;
  266. this.chunkPos = 0; // Position of current block in chunk
  267. this.chunksDone = 0; // How many chunks we already have
  268. this.leafLen = leafLen;
  269. this.personalization = abytesOrZero(opts.personalization);
  270. }
  271. update(data) {
  272. data = (0, utils_ts_1.toBytes)(data);
  273. (0, utils_ts_1.abytes)(data);
  274. const { chunkLen, blockLen, leafLen, rounds } = this;
  275. for (let pos = 0, len = data.length; pos < len;) {
  276. if (this.chunkPos == chunkLen) {
  277. if (this.leafHash)
  278. super.update(this.leafHash.digest());
  279. else {
  280. this.suffix = 0x06; // Its safe to change suffix here since its used only in digest()
  281. super.update(Uint8Array.from([3, 0, 0, 0, 0, 0, 0, 0]));
  282. }
  283. this.leafHash = new sha3_ts_1.Keccak(blockLen, 0x0b, leafLen, false, rounds);
  284. this.chunksDone++;
  285. this.chunkPos = 0;
  286. }
  287. const take = Math.min(chunkLen - this.chunkPos, len - pos);
  288. const chunk = data.subarray(pos, pos + take);
  289. if (this.leafHash)
  290. this.leafHash.update(chunk);
  291. else
  292. super.update(chunk);
  293. this.chunkPos += take;
  294. pos += take;
  295. }
  296. return this;
  297. }
  298. finish() {
  299. if (this.finished)
  300. return;
  301. const { personalization } = this;
  302. this.update(personalization).update(rightEncodeK12(personalization.length));
  303. // Leaf hash
  304. if (this.leafHash) {
  305. super.update(this.leafHash.digest());
  306. super.update(rightEncodeK12(this.chunksDone));
  307. super.update(Uint8Array.from([0xff, 0xff]));
  308. }
  309. super.finish.call(this);
  310. }
  311. destroy() {
  312. super.destroy.call(this);
  313. if (this.leafHash)
  314. this.leafHash.destroy();
  315. // We cannot zero personalization buffer since it is user provided and we don't want to mutate user input
  316. this.personalization = EMPTY_BUFFER;
  317. }
  318. _cloneInto(to) {
  319. const { blockLen, leafLen, leafHash, outputLen, rounds } = this;
  320. to || (to = new KangarooTwelve(blockLen, leafLen, outputLen, rounds, {}));
  321. super._cloneInto(to);
  322. if (leafHash)
  323. to.leafHash = leafHash._cloneInto(to.leafHash);
  324. to.personalization.set(this.personalization);
  325. to.leafLen = this.leafLen;
  326. to.chunkPos = this.chunkPos;
  327. to.chunksDone = this.chunksDone;
  328. return to;
  329. }
  330. clone() {
  331. return this._cloneInto();
  332. }
  333. }
  334. exports.KangarooTwelve = KangarooTwelve;
  335. /** KangarooTwelve: reduced 12-round keccak. */
  336. exports.k12 = (() => (0, utils_ts_1.createOptHasher)((opts = {}) => new KangarooTwelve(168, 32, chooseLen(opts, 32), 12, opts)))();
  337. /** MarsupilamiFourteen: reduced 14-round keccak. */
  338. exports.m14 = (() => (0, utils_ts_1.createOptHasher)((opts = {}) => new KangarooTwelve(136, 64, chooseLen(opts, 64), 14, opts)))();
  339. /**
  340. * More at https://github.com/XKCP/XKCP/tree/master/lib/high/Keccak/PRG.
  341. */
  342. class KeccakPRG extends sha3_ts_1.Keccak {
  343. constructor(capacity) {
  344. (0, utils_ts_1.anumber)(capacity);
  345. // Rho should be full bytes
  346. if (capacity < 0 || capacity > 1600 - 10 || (1600 - capacity - 2) % 8)
  347. throw new Error('invalid capacity');
  348. // blockLen = rho in bytes
  349. super((1600 - capacity - 2) / 8, 0, 0, true);
  350. this.rate = 1600 - capacity;
  351. this.posOut = Math.floor((this.rate + 7) / 8);
  352. }
  353. keccak() {
  354. // Duplex padding
  355. this.state[this.pos] ^= 0x01;
  356. this.state[this.blockLen] ^= 0x02; // Rho is full bytes
  357. super.keccak();
  358. this.pos = 0;
  359. this.posOut = 0;
  360. }
  361. update(data) {
  362. super.update(data);
  363. this.posOut = this.blockLen;
  364. return this;
  365. }
  366. feed(data) {
  367. return this.update(data);
  368. }
  369. finish() { }
  370. digestInto(_out) {
  371. throw new Error('digest is not allowed, use .fetch instead');
  372. }
  373. fetch(bytes) {
  374. return this.xof(bytes);
  375. }
  376. // Ensure irreversibility (even if state leaked previous outputs cannot be computed)
  377. forget() {
  378. if (this.rate < 1600 / 2 + 1)
  379. throw new Error('rate is too low to use .forget()');
  380. this.keccak();
  381. for (let i = 0; i < this.blockLen; i++)
  382. this.state[i] = 0;
  383. this.pos = this.blockLen;
  384. this.keccak();
  385. this.posOut = this.blockLen;
  386. }
  387. _cloneInto(to) {
  388. const { rate } = this;
  389. to || (to = new KeccakPRG(1600 - rate));
  390. super._cloneInto(to);
  391. to.rate = rate;
  392. return to;
  393. }
  394. clone() {
  395. return this._cloneInto();
  396. }
  397. }
  398. exports.KeccakPRG = KeccakPRG;
  399. /** KeccakPRG: Pseudo-random generator based on Keccak. https://keccak.team/files/CSF-0.1.pdf */
  400. const keccakprg = (capacity = 254) => new KeccakPRG(capacity);
  401. exports.keccakprg = keccakprg;
  402. //# sourceMappingURL=sha3-addons.js.map