sha1.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. function encodeUTF8(s) {
  2. var i, r = [], c, x;
  3. for (i = 0; i < s.length; i++)
  4. if ((c = s.charCodeAt(i)) < 0x80) r.push(c);
  5. else if (c < 0x800) r.push(0xC0 + (c >> 6 & 0x1F), 0x80 + (c & 0x3F));
  6. else {
  7. if ((x = c ^ 0xD800) >> 10 == 0) //对四字节UTF-16转换为Unicode
  8. c = (x << 10) + (s.charCodeAt(++i) ^ 0xDC00) + 0x10000,
  9. r.push(0xF0 + (c >> 18 & 0x7), 0x80 + (c >> 12 & 0x3F));
  10. else r.push(0xE0 + (c >> 12 & 0xF));
  11. r.push(0x80 + (c >> 6 & 0x3F), 0x80 + (c & 0x3F));
  12. };
  13. return r;
  14. }
  15. // 字符串加密成 hex 字符串
  16. function sha1(s) {
  17. var data = new Uint8Array(encodeUTF8(s))
  18. var i, j, t;
  19. var l = ((data.length + 8) >>> 6 << 4) + 16, s = new Uint8Array(l << 2);
  20. s.set(new Uint8Array(data.buffer)), s = new Uint32Array(s.buffer);
  21. for (t = new DataView(s.buffer), i = 0; i < l; i++)s[i] = t.getUint32(i << 2);
  22. s[data.length >> 2] |= 0x80 << (24 - (data.length & 3) * 8);
  23. s[l - 1] = data.length << 3;
  24. var w = [], f = [
  25. function () { return m[1] & m[2] | ~m[1] & m[3]; },
  26. function () { return m[1] ^ m[2] ^ m[3]; },
  27. function () { return m[1] & m[2] | m[1] & m[3] | m[2] & m[3]; },
  28. function () { return m[1] ^ m[2] ^ m[3]; }
  29. ], rol = function (n, c) { return n << c | n >>> (32 - c); },
  30. k = [1518500249, 1859775393, -1894007588, -899497514],
  31. m = [1732584193, -271733879, null, null, -1009589776];
  32. m[2] = ~m[0], m[3] = ~m[1];
  33. for (i = 0; i < s.length; i += 16) {
  34. var o = m.slice(0);
  35. for (j = 0; j < 80; j++)
  36. w[j] = j < 16 ? s[i + j] : rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1),
  37. t = rol(m[0], 5) + f[j / 20 | 0]() + m[4] + w[j] + k[j / 20 | 0] | 0,
  38. m[1] = rol(m[1], 30), m.pop(), m.unshift(t);
  39. for (j = 0; j < 5; j++)m[j] = m[j] + o[j] | 0;
  40. };
  41. t = new DataView(new Uint32Array(m).buffer);
  42. for (var i = 0; i < 5; i++)m[i] = t.getUint32(i << 2);
  43. var hex = Array.prototype.map.call(new Uint8Array(new Uint32Array(m).buffer), function (e) {
  44. return (e < 16 ? "0" : "") + e.toString(16);
  45. }).join("");
  46. return hex;
  47. }
  48. export default sha1