sha1.uts
2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/**
* SHA1 算法(从 gl_tape/lib/sha1.js 迁移为 UTS)
* 字符串加密成 hex 字符串
*/
function encodeUTF8(s: string): number[] {
const r: number[] = [];
let i = 0;
while (i < s.length) {
const c = s.charCodeAt(i) as number;
if (c < 0x80) {
r.push(c);
} else if (c < 0x800) {
r.push(0xc0 + ((c >> 6) & 0x1f), 0x80 + (c & 0x3f));
} else {
const x = c ^ 0xd800;
if (x >> 10 == 0) {
const next = (s.charCodeAt(i + 1) as number) ^ 0xdc00;
const code = (x << 10) + next + 0x10000;
r.push(0xf0 + ((code >> 18) & 0x7), 0x80 + ((code >> 12) & 0x3f));
i++;
} else {
r.push(0xe0 + ((c >> 12) & 0xf));
}
r.push(0x80 + ((c >> 6) & 0x3f), 0x80 + (c & 0x3f));
}
i++;
}
return r;
}
export function sha1(s: string): string {
const data = new Uint8Array(encodeUTF8(s));
const l = ((data.length + 8) >>> 6 << 4) + 16;
const sBuf = new ArrayBuffer(l << 2);
const sView = new Uint8Array(sBuf);
sView.set(data);
const s32 = new Uint32Array(sBuf);
const t = new DataView(sBuf);
let i = 0;
while (i < l) {
s32[i] = t.getUint32(i << 2, false);
i++;
}
s32[data.length >> 2] |= 0x80 << (24 - (data.length & 3) * 8);
s32[l - 1] = data.length << 3;
const w: number[] = [];
// 预先初始化 w 数组为 80 个元素,避免 UTS 下标越界
let wInit = 0;
while (wInit < 80) {
w.push(0);
wInit++;
}
const k = [1518500249, 1859775393, -1894007588, -899497514];
let m0 = 1732584193;
let m1 = -271733879;
let m2 = 0;
let m3 = 0;
let m4 = -1009589776;
m2 = ~m0;
m3 = ~m1;
const rol = (n: number, c: number): number => (n << c) | (n >>> (32 - c));
const f0 = (): number => (m1 & m2) | (~m1 & m3);
const f1 = (): number => m1 ^ m2 ^ m3;
const f2 = (): number => (m1 & m2) | (m1 & m3) | (m2 & m3);
const f3 = (): number => m1 ^ m2 ^ m3;
i = 0;
while (i < s32.length) {
const o0 = m0;
const o1 = m1;
const o2 = m2;
const o3 = m3;
const o4 = m4;
let j = 0;
while (j < 80) {
const wj = j < 16 ? s32[i + j] : rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
w[j] = wj;
const f = j < 20 ? f0() : j < 40 ? f1() : j < 60 ? f2() : f3();
const kj = k[Math.floor(j / 20)];
const tVal = (rol(m0, 5) + f + m4 + wj + kj) | 0;
m4 = m3;
m3 = m2;
m2 = rol(m1, 30);
m1 = m0;
m0 = tVal;
j++;
}
m0 = (m0 + o0) | 0;
m1 = (m1 + o1) | 0;
m2 = (m2 + o2) | 0;
m3 = (m3 + o3) | 0;
m4 = (m4 + o4) | 0;
i += 16;
}
const outBuf = new ArrayBuffer(20);
const outView = new DataView(outBuf);
outView.setUint32(0, m0);
outView.setUint32(4, m1);
outView.setUint32(8, m2);
outView.setUint32(12, m3);
outView.setUint32(16, m4);
const bytes = new Uint8Array(outBuf);
let hex = "";
let hi = 0;
while (hi < bytes.length) {
const e = bytes[hi];
hex += (e < 16 ? "0" : "") + e.toString(16);
hi++;
}
return hex;
}