sha3-addons.js 14 KB

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