1 | function f(s, x, y, z) {
|
---|
2 | switch (s) {
|
---|
3 | case 0:
|
---|
4 | return (x & y) ^ (~x & z);
|
---|
5 | case 1:
|
---|
6 | return x ^ y ^ z;
|
---|
7 | case 2:
|
---|
8 | return (x & y) ^ (x & z) ^ (y & z);
|
---|
9 | case 3:
|
---|
10 | return x ^ y ^ z;
|
---|
11 | }
|
---|
12 | }
|
---|
13 | function ROTL(x, n) {
|
---|
14 | return (x << n) | (x >>> (32 - n));
|
---|
15 | }
|
---|
16 | function sha1(bytes) {
|
---|
17 | const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
|
---|
18 | const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
|
---|
19 | const newBytes = new Uint8Array(bytes.length + 1);
|
---|
20 | newBytes.set(bytes);
|
---|
21 | newBytes[bytes.length] = 0x80;
|
---|
22 | bytes = newBytes;
|
---|
23 | const l = bytes.length / 4 + 2;
|
---|
24 | const N = Math.ceil(l / 16);
|
---|
25 | const M = new Array(N);
|
---|
26 | for (let i = 0; i < N; ++i) {
|
---|
27 | const arr = new Uint32Array(16);
|
---|
28 | for (let j = 0; j < 16; ++j) {
|
---|
29 | arr[j] =
|
---|
30 | (bytes[i * 64 + j * 4] << 24) |
|
---|
31 | (bytes[i * 64 + j * 4 + 1] << 16) |
|
---|
32 | (bytes[i * 64 + j * 4 + 2] << 8) |
|
---|
33 | bytes[i * 64 + j * 4 + 3];
|
---|
34 | }
|
---|
35 | M[i] = arr;
|
---|
36 | }
|
---|
37 | M[N - 1][14] = ((bytes.length - 1) * 8) / Math.pow(2, 32);
|
---|
38 | M[N - 1][14] = Math.floor(M[N - 1][14]);
|
---|
39 | M[N - 1][15] = ((bytes.length - 1) * 8) & 0xffffffff;
|
---|
40 | for (let i = 0; i < N; ++i) {
|
---|
41 | const W = new Uint32Array(80);
|
---|
42 | for (let t = 0; t < 16; ++t) {
|
---|
43 | W[t] = M[i][t];
|
---|
44 | }
|
---|
45 | for (let t = 16; t < 80; ++t) {
|
---|
46 | W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1);
|
---|
47 | }
|
---|
48 | let a = H[0];
|
---|
49 | let b = H[1];
|
---|
50 | let c = H[2];
|
---|
51 | let d = H[3];
|
---|
52 | let e = H[4];
|
---|
53 | for (let t = 0; t < 80; ++t) {
|
---|
54 | const s = Math.floor(t / 20);
|
---|
55 | const T = (ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t]) >>> 0;
|
---|
56 | e = d;
|
---|
57 | d = c;
|
---|
58 | c = ROTL(b, 30) >>> 0;
|
---|
59 | b = a;
|
---|
60 | a = T;
|
---|
61 | }
|
---|
62 | H[0] = (H[0] + a) >>> 0;
|
---|
63 | H[1] = (H[1] + b) >>> 0;
|
---|
64 | H[2] = (H[2] + c) >>> 0;
|
---|
65 | H[3] = (H[3] + d) >>> 0;
|
---|
66 | H[4] = (H[4] + e) >>> 0;
|
---|
67 | }
|
---|
68 | return Uint8Array.of(H[0] >> 24, H[0] >> 16, H[0] >> 8, H[0], H[1] >> 24, H[1] >> 16, H[1] >> 8, H[1], H[2] >> 24, H[2] >> 16, H[2] >> 8, H[2], H[3] >> 24, H[3] >> 16, H[3] >> 8, H[3], H[4] >> 24, H[4] >> 16, H[4] >> 8, H[4]);
|
---|
69 | }
|
---|
70 | export default sha1;
|
---|