function sha1(message) {
function rotateLeft(n, s) {
return (n << s) | (n >>> (32 - s));
}
function toHex(value) {
var hex = "";
for (var i = 0; i < 8; i++) {
hex += ((value >>> (28 - i * 4)) & 0xf).toString(16);
}
return hex;
}
function preProcessMessage(message) {
var originalLength = message.length * 8;
var appendedOne = 1 << 7;
message.push(appendedOne);
while (message.length % 64 !== 56) {
message.push(0);
}
var lengthBytes = new Array(8);
for (var i = 0; i < 8; i++) {
lengthBytes[i] = (originalLength >>> (56 - i * 8)) & 0xff;
}
message = message.concat(lengthBytes);
return message;
}
var h0 = 0x67452301;
var h1 = 0xefcdab89;
var h2 = 0x98badcfe;
var h3 = 0x10325476;
var h4 = 0xc3d2e1f0;
var messageBytes = [];
for (var i = 0; i < message.length; i++) {
messageBytes.push(message.charCodeAt(i) & 0xff);
}
messageBytes = preProcessMessage(messageBytes);
var blocks = messageBytes.length / 64;
for (var i = 0; i < blocks; i++) {
var words = new Array(80);
for (var j = 0; j < 16; j++) {
words[j] = (messageBytes[i * 64 + j * 4] << 24) |
(messageBytes[i * 64 + j * 4 + 1] << 16) |
(messageBytes[i * 64 + j * 4 + 2] << 8) |
(messageBytes[i * 64 + j * 4 + 3]);
}
for (var j = 16; j < 80; j++) {
words[j] = rotateLeft((words[j - 3] ^ words[j - 8] ^ words[j - 14] ^ words[j - 16]), 1);
}
var a = h0;
var b = h1;
var c = h2;
var d = h3;
var e = h4;
for (var j = 0; j < 80; j++) {
var f, k;
if (j < 20) {
f = (b & c) | ((~b) & d);
k = 0x5a827999;
} else if (j < 40) {
f = b ^ c ^ d;
k = 0x6ed9eba1;
} else if (j < 60) {
f = (b & c) | (b & d) | (c & d);
k = 0x8f1bbcdc;
} else {
f = b ^ c ^ d;
k = 0xca62c1d6;
}
var temp = rotateLeft(a, 5) + f + e + k + words[j];
e = d;
d = c;
c = rotateLeft(b, 30);
b = a;
a = temp;
}
h0 += a;
h1 += b;
h2 += c;
h3 += d;
h4 += e;
}
var hash = toHex(h0) + toHex(h1) + toHex(h2) + toHex(h3) + toHex(h4);
return hash;
}
// 示例用法
var plaintext = "Hello, SHA-1!";
var hashedText = sha1(plaintext);
console.log("Hashed Text:", hashedText);