租房小程序前端代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
2.3 KiB

3 months ago
  1. /*
  2. * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
  3. * in FIPS PUB 180-1
  4. * Version 2.1a Copyright Paul Johnston 2000 - 2002.
  5. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  6. * Distributed under the BSD License
  7. * See http://pajhome.org.uk/crypt/md5 for details.
  8. */
  9. var helpers = require('./helpers');
  10. /*
  11. * Calculate the SHA-1 of an array of big-endian words, and a bit length
  12. */
  13. function core_sha1(x, len) {
  14. /* append padding */
  15. x[len >> 5] |= 0x80 << (24 - (len % 32));
  16. x[(((len + 64) >> 9) << 4) + 15] = len;
  17. var w = Array(80);
  18. var a = 1732584193;
  19. var b = -271733879;
  20. var c = -1732584194;
  21. var d = 271733878;
  22. var e = -1009589776;
  23. for (var i = 0; i < x.length; i += 16) {
  24. var olda = a;
  25. var oldb = b;
  26. var oldc = c;
  27. var oldd = d;
  28. var olde = e;
  29. for (var j = 0; j < 80; j++) {
  30. if (j < 16) w[j] = x[i + j];
  31. else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
  32. var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));
  33. e = d;
  34. d = c;
  35. c = rol(b, 30);
  36. b = a;
  37. a = t;
  38. }
  39. a = safe_add(a, olda);
  40. b = safe_add(b, oldb);
  41. c = safe_add(c, oldc);
  42. d = safe_add(d, oldd);
  43. e = safe_add(e, olde);
  44. }
  45. return Array(a, b, c, d, e);
  46. }
  47. /*
  48. * Perform the appropriate triplet combination function for the current
  49. * iteration
  50. */
  51. function sha1_ft(t, b, c, d) {
  52. if (t < 20) return (b & c) | (~b & d);
  53. if (t < 40) return b ^ c ^ d;
  54. if (t < 60) return (b & c) | (b & d) | (c & d);
  55. return b ^ c ^ d;
  56. }
  57. /*
  58. * Determine the appropriate additive constant for the current iteration
  59. */
  60. function sha1_kt(t) {
  61. return t < 20 ? 1518500249 : t < 40 ? 1859775393 : t < 60 ? -1894007588 : -899497514;
  62. }
  63. /*
  64. * Add integers, wrapping at 2^32. This uses 16-bit operations internally
  65. * to work around bugs in some JS interpreters.
  66. */
  67. function safe_add(x, y) {
  68. var lsw = (x & 0xffff) + (y & 0xffff);
  69. var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  70. return (msw << 16) | (lsw & 0xffff);
  71. }
  72. /*
  73. * Bitwise rotate a 32-bit number to the left.
  74. */
  75. function rol(num, cnt) {
  76. return (num << cnt) | (num >>> (32 - cnt));
  77. }
  78. module.exports = function sha1(buf) {
  79. return helpers.hash(buf, core_sha1, 20, true);
  80. };