sha1.uts 2.78 KB
/**
 * 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;
}