sha3-addons.js 16 KB

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