sha3.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. /**
  2. * SHA3 (keccak) hash function, based on a new "Sponge function" design.
  3. * Different from older hashes, the internal state is bigger than output size.
  4. *
  5. * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),
  6. * [Website](https://keccak.team/keccak.html),
  7. * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).
  8. *
  9. * Check out `sha3-addons` module for cSHAKE, k12, and others.
  10. * @module
  11. */
  12. import { rotlBH, rotlBL, rotlSH, rotlSL, split } from "./_u64.js";
  13. // prettier-ignore
  14. import { abytes, aexists, anumber, aoutput, clean, createHasher, createXOFer, Hash, swap32IfBE, toBytes, u32 } from "./utils.js";
  15. // No __PURE__ annotations in sha3 header:
  16. // EVERYTHING is in fact used on every export.
  17. // Various per round constants calculations
  18. const _0n = BigInt(0);
  19. const _1n = BigInt(1);
  20. const _2n = BigInt(2);
  21. const _7n = BigInt(7);
  22. const _256n = BigInt(256);
  23. const _0x71n = BigInt(0x71);
  24. const SHA3_PI = [];
  25. const SHA3_ROTL = [];
  26. const _SHA3_IOTA = [];
  27. for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
  28. // Pi
  29. [x, y] = [y, (2 * x + 3 * y) % 5];
  30. SHA3_PI.push(2 * (5 * y + x));
  31. // Rotational
  32. SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);
  33. // Iota
  34. let t = _0n;
  35. for (let j = 0; j < 7; j++) {
  36. R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;
  37. if (R & _2n)
  38. t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);
  39. }
  40. _SHA3_IOTA.push(t);
  41. }
  42. const IOTAS = split(_SHA3_IOTA, true);
  43. const SHA3_IOTA_H = IOTAS[0];
  44. const SHA3_IOTA_L = IOTAS[1];
  45. // Left rotation (without 0, 32, 64)
  46. const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));
  47. const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));
  48. /** `keccakf1600` internal function, additionally allows to adjust round count. */
  49. export function keccakP(s, rounds = 24) {
  50. const B = new Uint32Array(5 * 2);
  51. // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)
  52. for (let round = 24 - rounds; round < 24; round++) {
  53. // Theta θ
  54. for (let x = 0; x < 10; x++)
  55. B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
  56. for (let x = 0; x < 10; x += 2) {
  57. const idx1 = (x + 8) % 10;
  58. const idx0 = (x + 2) % 10;
  59. const B0 = B[idx0];
  60. const B1 = B[idx0 + 1];
  61. const Th = rotlH(B0, B1, 1) ^ B[idx1];
  62. const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
  63. for (let y = 0; y < 50; y += 10) {
  64. s[x + y] ^= Th;
  65. s[x + y + 1] ^= Tl;
  66. }
  67. }
  68. // Rho (ρ) and Pi (π)
  69. let curH = s[2];
  70. let curL = s[3];
  71. for (let t = 0; t < 24; t++) {
  72. const shift = SHA3_ROTL[t];
  73. const Th = rotlH(curH, curL, shift);
  74. const Tl = rotlL(curH, curL, shift);
  75. const PI = SHA3_PI[t];
  76. curH = s[PI];
  77. curL = s[PI + 1];
  78. s[PI] = Th;
  79. s[PI + 1] = Tl;
  80. }
  81. // Chi (χ)
  82. for (let y = 0; y < 50; y += 10) {
  83. for (let x = 0; x < 10; x++)
  84. B[x] = s[y + x];
  85. for (let x = 0; x < 10; x++)
  86. s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
  87. }
  88. // Iota (ι)
  89. s[0] ^= SHA3_IOTA_H[round];
  90. s[1] ^= SHA3_IOTA_L[round];
  91. }
  92. clean(B);
  93. }
  94. /** Keccak sponge function. */
  95. export class Keccak extends Hash {
  96. // NOTE: we accept arguments in bytes instead of bits here.
  97. constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
  98. super();
  99. this.pos = 0;
  100. this.posOut = 0;
  101. this.finished = false;
  102. this.destroyed = false;
  103. this.enableXOF = false;
  104. this.blockLen = blockLen;
  105. this.suffix = suffix;
  106. this.outputLen = outputLen;
  107. this.enableXOF = enableXOF;
  108. this.rounds = rounds;
  109. // Can be passed from user as dkLen
  110. anumber(outputLen);
  111. // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes
  112. // 0 < blockLen < 200
  113. if (!(0 < blockLen && blockLen < 200))
  114. throw new Error('only keccak-f1600 function is supported');
  115. this.state = new Uint8Array(200);
  116. this.state32 = u32(this.state);
  117. }
  118. clone() {
  119. return this._cloneInto();
  120. }
  121. keccak() {
  122. swap32IfBE(this.state32);
  123. keccakP(this.state32, this.rounds);
  124. swap32IfBE(this.state32);
  125. this.posOut = 0;
  126. this.pos = 0;
  127. }
  128. update(data) {
  129. aexists(this);
  130. data = toBytes(data);
  131. abytes(data);
  132. const { blockLen, state } = this;
  133. const len = data.length;
  134. for (let pos = 0; pos < len;) {
  135. const take = Math.min(blockLen - this.pos, len - pos);
  136. for (let i = 0; i < take; i++)
  137. state[this.pos++] ^= data[pos++];
  138. if (this.pos === blockLen)
  139. this.keccak();
  140. }
  141. return this;
  142. }
  143. finish() {
  144. if (this.finished)
  145. return;
  146. this.finished = true;
  147. const { state, suffix, pos, blockLen } = this;
  148. // Do the padding
  149. state[pos] ^= suffix;
  150. if ((suffix & 0x80) !== 0 && pos === blockLen - 1)
  151. this.keccak();
  152. state[blockLen - 1] ^= 0x80;
  153. this.keccak();
  154. }
  155. writeInto(out) {
  156. aexists(this, false);
  157. abytes(out);
  158. this.finish();
  159. const bufferOut = this.state;
  160. const { blockLen } = this;
  161. for (let pos = 0, len = out.length; pos < len;) {
  162. if (this.posOut >= blockLen)
  163. this.keccak();
  164. const take = Math.min(blockLen - this.posOut, len - pos);
  165. out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
  166. this.posOut += take;
  167. pos += take;
  168. }
  169. return out;
  170. }
  171. xofInto(out) {
  172. // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF
  173. if (!this.enableXOF)
  174. throw new Error('XOF is not possible for this instance');
  175. return this.writeInto(out);
  176. }
  177. xof(bytes) {
  178. anumber(bytes);
  179. return this.xofInto(new Uint8Array(bytes));
  180. }
  181. digestInto(out) {
  182. aoutput(out, this);
  183. if (this.finished)
  184. throw new Error('digest() was already called');
  185. this.writeInto(out);
  186. this.destroy();
  187. return out;
  188. }
  189. digest() {
  190. return this.digestInto(new Uint8Array(this.outputLen));
  191. }
  192. destroy() {
  193. this.destroyed = true;
  194. clean(this.state);
  195. }
  196. _cloneInto(to) {
  197. const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
  198. to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
  199. to.state32.set(this.state32);
  200. to.pos = this.pos;
  201. to.posOut = this.posOut;
  202. to.finished = this.finished;
  203. to.rounds = rounds;
  204. // Suffix can change in cSHAKE
  205. to.suffix = suffix;
  206. to.outputLen = outputLen;
  207. to.enableXOF = enableXOF;
  208. to.destroyed = this.destroyed;
  209. return to;
  210. }
  211. }
  212. const gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen));
  213. /** SHA3-224 hash function. */
  214. export const sha3_224 = /* @__PURE__ */ (() => gen(0x06, 144, 224 / 8))();
  215. /** SHA3-256 hash function. Different from keccak-256. */
  216. export const sha3_256 = /* @__PURE__ */ (() => gen(0x06, 136, 256 / 8))();
  217. /** SHA3-384 hash function. */
  218. export const sha3_384 = /* @__PURE__ */ (() => gen(0x06, 104, 384 / 8))();
  219. /** SHA3-512 hash function. */
  220. export const sha3_512 = /* @__PURE__ */ (() => gen(0x06, 72, 512 / 8))();
  221. /** keccak-224 hash function. */
  222. export const keccak_224 = /* @__PURE__ */ (() => gen(0x01, 144, 224 / 8))();
  223. /** keccak-256 hash function. Different from SHA3-256. */
  224. export const keccak_256 = /* @__PURE__ */ (() => gen(0x01, 136, 256 / 8))();
  225. /** keccak-384 hash function. */
  226. export const keccak_384 = /* @__PURE__ */ (() => gen(0x01, 104, 384 / 8))();
  227. /** keccak-512 hash function. */
  228. export const keccak_512 = /* @__PURE__ */ (() => gen(0x01, 72, 512 / 8))();
  229. const genShake = (suffix, blockLen, outputLen) => createXOFer((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true));
  230. /** SHAKE128 XOF with 128-bit security. */
  231. export const shake128 = /* @__PURE__ */ (() => genShake(0x1f, 168, 128 / 8))();
  232. /** SHAKE256 XOF with 256-bit security. */
  233. export const shake256 = /* @__PURE__ */ (() => genShake(0x1f, 136, 256 / 8))();
  234. //# sourceMappingURL=sha3.js.map