js实现sha1
使用原生 JavaScript 实现 SHA-1
SHA-1(安全散列算法 1)是一种常见的加密哈希函数。以下是原生 JavaScript 的实现方法:
function sha1(msg) {
function rotate_left(n, s) {
return (n << s) | (n >>> (32 - s));
}
function lsb_hex(val) {
let str = '';
for (let i = 0; i <= 6; i += 2) {
str += String.fromCharCode(parseInt(val.substr(i, 2), 16));
}
return str;
}
function cvt_hex(val) {
let str = '';
for (let i = 7; i >= 0; i--) {
str += ((val >>> (i * 4)) & 0x0f).toString(16);
}
return str;
}
msg = msg + String.fromCharCode(0x80);
while ((msg.length % 64) < 56) {
msg += String.fromCharCode(0x00);
}
msg += lsb_hex((msg.length / 4).toString(16).padStart(16, '0'));
const block_size = 16;
const word_array = [];
for (let i = 0; i < msg.length; i += 4) {
word_array.push(
(msg.charCodeAt(i) << 24) |
(msg.charCodeAt(i + 1) << 16) |
(msg.charCodeAt(i + 2) << 8) |
msg.charCodeAt(i + 3)
);
}
let h0 = 0x67452301;
let h1 = 0xEFCDAB89;
let h2 = 0x98BADCFE;
let h3 = 0x10325476;
let h4 = 0xC3D2E1F0;
for (let block_start = 0; block_start < word_array.length; block_start += block_size) {
const w = new Array(80);
for (let i = 0; i < 16; i++) {
w[i] = word_array[block_start + i];
}
for (let i = 16; i < 80; i++) {
w[i] = rotate_left(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
}
let a = h0;
let b = h1;
let c = h2;
let d = h3;
let e = h4;
for (let i = 0; i < 80; i++) {
let f, k;
if (i < 20) {
f = (b & c) | ((~b) & d);
k = 0x5A827999;
} else if (i < 40) {
f = b ^ c ^ d;
k = 0x6ED9EBA1;
} else if (i < 60) {
f = (b & c) | (b & d) | (c & d);
k = 0x8F1BBCDC;
} else {
f = b ^ c ^ d;
k = 0xCA62C1D6;
}
const temp = (rotate_left(a, 5) + f + e + k + w[i]) & 0xFFFFFFFF;
e = d;
d = c;
c = rotate_left(b, 30);
b = a;
a = temp;
}
h0 = (h0 + a) & 0xFFFFFFFF;
h1 = (h1 + b) & 0xFFFFFFFF;
h2 = (h2 + c) & 0xFFFFFFFF;
h3 = (h3 + d) & 0xFFFFFFFF;
h4 = (h4 + e) & 0xFFFFFFFF;
}
return cvt_hex(h0) + cvt_hex(h1) + cvt_hex(h2) + cvt_hex(h3) + cvt_hex(h4);
}
使用 Web Crypto API 实现 SHA-1
现代浏览器提供了更高效的加密 API:

async function sha1(message) {
const msgBuffer = new TextEncoder().encode(message);
const hashBuffer = await crypto.subtle.digest('SHA-1', msgBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}
// 使用示例
sha1('hello').then(console.log); // 输出: aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d
使用第三方库实现 SHA-1
对于 Node.js 或需要更全面解决方案的场景,可以使用 crypto 模块或第三方库:
Node.js 内置 crypto 模块:

const crypto = require('crypto');
function sha1(input) {
return crypto.createHash('sha1').update(input).digest('hex');
}
使用 jsSHA 库:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsSHA/3.2.0/sha.js"></script>
<script>
const shaObj = new jsSHA("SHA-1", "TEXT");
shaObj.update("message");
const hash = shaObj.getHash("HEX");
</script>
注意事项
SHA-1 已被证明存在安全漏洞,不应用于密码存储或高安全性场景。对于新项目,建议使用更安全的算法如 SHA-256 或 SHA-3。
原生实现主要适用于学习目的,生产环境推荐使用浏览器内置 API 或经过验证的库,它们经过优化且更可靠。






