sha1.ts 2.2 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<SHA1> {
  12. private A = SHA1_IV[0] | 0;
  13. private B = SHA1_IV[1] | 0;
  14. private C = SHA1_IV[2] | 0;
  15. private D = SHA1_IV[3] | 0;
  16. private E = SHA1_IV[4] | 0;
  17. constructor() {
  18. super(64, 20, 8, false);
  19. }
  20. protected get(): [number, number, number, number, number] {
  21. const { A, B, C, D, E } = this;
  22. return [A, B, C, D, E];
  23. }
  24. protected set(A: number, B: number, C: number, D: number, E: number) {
  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. protected process(view: DataView, offset: number): void {
  32. for (let i = 0; i < 16; i++, offset += 4) SHA1_W[i] = view.getUint32(offset, false);
  33. for (let i = 16; i < 80; i++)
  34. SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);
  35. // Compression function main loop, 80 rounds
  36. let { A, B, C, D, E } = this;
  37. for (let i = 0; i < 80; i++) {
  38. let F, K;
  39. if (i < 20) {
  40. F = Chi(B, C, D);
  41. K = 0x5a827999;
  42. } else if (i < 40) {
  43. F = B ^ C ^ D;
  44. K = 0x6ed9eba1;
  45. } else if (i < 60) {
  46. F = Maj(B, C, D);
  47. K = 0x8f1bbcdc;
  48. } else {
  49. F = B ^ C ^ D;
  50. K = 0xca62c1d6;
  51. }
  52. const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;
  53. E = D;
  54. D = C;
  55. C = rotl(B, 30);
  56. B = A;
  57. A = T;
  58. }
  59. // Add the compressed chunk to the current hash value
  60. A = (A + this.A) | 0;
  61. B = (B + this.B) | 0;
  62. C = (C + this.C) | 0;
  63. D = (D + this.D) | 0;
  64. E = (E + this.E) | 0;
  65. this.set(A, B, C, D, E);
  66. }
  67. protected roundClean() {
  68. SHA1_W.fill(0);
  69. }
  70. destroy() {
  71. this.set(0, 0, 0, 0, 0);
  72. this.buffer.fill(0);
  73. }
  74. }
  75. export const sha1 = /* @__PURE__ */ wrapConstructor(() => new SHA1());