sha1.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // Adapted from Chris Veness' SHA1 code at
  2. // http://www.movable-type.co.uk/scripts/sha1.html
  3. function f(s, x, y, z) {
  4. switch (s) {
  5. case 0:
  6. return x & y ^ ~x & z;
  7. case 1:
  8. return x ^ y ^ z;
  9. case 2:
  10. return x & y ^ x & z ^ y & z;
  11. case 3:
  12. return x ^ y ^ z;
  13. }
  14. }
  15. function ROTL(x, n) {
  16. return x << n | x >>> 32 - n;
  17. }
  18. function sha1(bytes) {
  19. var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
  20. var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
  21. if (typeof bytes === 'string') {
  22. var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
  23. bytes = [];
  24. for (var i = 0; i < msg.length; ++i) {
  25. bytes.push(msg.charCodeAt(i));
  26. }
  27. } else if (!Array.isArray(bytes)) {
  28. // Convert Array-like to Array
  29. bytes = Array.prototype.slice.call(bytes);
  30. }
  31. bytes.push(0x80);
  32. var l = bytes.length / 4 + 2;
  33. var N = Math.ceil(l / 16);
  34. var M = new Array(N);
  35. for (var _i = 0; _i < N; ++_i) {
  36. var arr = new Uint32Array(16);
  37. for (var j = 0; j < 16; ++j) {
  38. arr[j] = bytes[_i * 64 + j * 4] << 24 | bytes[_i * 64 + j * 4 + 1] << 16 | bytes[_i * 64 + j * 4 + 2] << 8 | bytes[_i * 64 + j * 4 + 3];
  39. }
  40. M[_i] = arr;
  41. }
  42. M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);
  43. M[N - 1][14] = Math.floor(M[N - 1][14]);
  44. M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;
  45. for (var _i2 = 0; _i2 < N; ++_i2) {
  46. var W = new Uint32Array(80);
  47. for (var t = 0; t < 16; ++t) {
  48. W[t] = M[_i2][t];
  49. }
  50. for (var _t = 16; _t < 80; ++_t) {
  51. W[_t] = ROTL(W[_t - 3] ^ W[_t - 8] ^ W[_t - 14] ^ W[_t - 16], 1);
  52. }
  53. var a = H[0];
  54. var b = H[1];
  55. var c = H[2];
  56. var d = H[3];
  57. var e = H[4];
  58. for (var _t2 = 0; _t2 < 80; ++_t2) {
  59. var s = Math.floor(_t2 / 20);
  60. var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[_t2] >>> 0;
  61. e = d;
  62. d = c;
  63. c = ROTL(b, 30) >>> 0;
  64. b = a;
  65. a = T;
  66. }
  67. H[0] = H[0] + a >>> 0;
  68. H[1] = H[1] + b >>> 0;
  69. H[2] = H[2] + c >>> 0;
  70. H[3] = H[3] + d >>> 0;
  71. H[4] = H[4] + e >>> 0;
  72. }
  73. return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff];
  74. }
  75. export default sha1;