sha3-addons.js 15 KB

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