sha1.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import { HashMD, Chi, Maj } from './_md.js';
  2. import { rotl, wrapConstructor } from './utils.js';
  3. // SHA1 (RFC 3174) was cryptographically broken. It's still used. Don't use it for a new protocol.
  4. // Initial state
  5. const SHA1_IV = /* @__PURE__ */ new Uint32Array([
  6. 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,
  7. ]);
  8. // Temporary buffer, not used to store anything between runs
  9. // Named this way because it matches specification.
  10. const SHA1_W = /* @__PURE__ */ new Uint32Array(80);
  11. class SHA1 extends HashMD {
  12. constructor() {
  13. super(64, 20, 8, false);
  14. this.A = SHA1_IV[0] | 0;
  15. this.B = SHA1_IV[1] | 0;
  16. this.C = SHA1_IV[2] | 0;
  17. this.D = SHA1_IV[3] | 0;
  18. this.E = SHA1_IV[4] | 0;
  19. }
  20. get() {
  21. const { A, B, C, D, E } = this;
  22. return [A, B, C, D, E];
  23. }
  24. set(A, B, C, D, E) {
  25. this.A = A | 0;
  26. this.B = B | 0;
  27. this.C = C | 0;
  28. this.D = D | 0;
  29. this.E = E | 0;
  30. }
  31. process(view, offset) {
  32. for (let i = 0; i < 16; i++, offset += 4)
  33. SHA1_W[i] = view.getUint32(offset, false);
  34. for (let i = 16; i < 80; i++)
  35. SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);
  36. // Compression function main loop, 80 rounds
  37. let { A, B, C, D, E } = this;
  38. for (let i = 0; i < 80; i++) {
  39. let F, K;
  40. if (i < 20) {
  41. F = Chi(B, C, D);
  42. K = 0x5a827999;
  43. }
  44. else if (i < 40) {
  45. F = B ^ C ^ D;
  46. K = 0x6ed9eba1;
  47. }
  48. else if (i < 60) {
  49. F = Maj(B, C, D);
  50. K = 0x8f1bbcdc;
  51. }
  52. else {
  53. F = B ^ C ^ D;
  54. K = 0xca62c1d6;
  55. }
  56. const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;
  57. E = D;
  58. D = C;
  59. C = rotl(B, 30);
  60. B = A;
  61. A = T;
  62. }
  63. // Add the compressed chunk to the current hash value
  64. A = (A + this.A) | 0;
  65. B = (B + this.B) | 0;
  66. C = (C + this.C) | 0;
  67. D = (D + this.D) | 0;
  68. E = (E + this.E) | 0;
  69. this.set(A, B, C, D, E);
  70. }
  71. roundClean() {
  72. SHA1_W.fill(0);
  73. }
  74. destroy() {
  75. this.set(0, 0, 0, 0, 0);
  76. this.buffer.fill(0);
  77. }
  78. }
  79. export const sha1 = /* @__PURE__ */ wrapConstructor(() => new SHA1());
  80. //# sourceMappingURL=sha1.js.map