sha.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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. {
  15. /* append padding */
  16. x[len >> 5] |= 0x80 << (24 - len % 32);
  17. x[((len + 64 >> 9) << 4) + 15] = len;
  18. var w = Array(80);
  19. var a = 1732584193;
  20. var b = -271733879;
  21. var c = -1732584194;
  22. var d = 271733878;
  23. var e = -1009589776;
  24. for(var i = 0; i < x.length; i += 16)
  25. {
  26. var olda = a;
  27. var oldb = b;
  28. var oldc = c;
  29. var oldd = d;
  30. var olde = e;
  31. for(var j = 0; j < 80; j++)
  32. {
  33. if(j < 16) w[j] = x[i + j];
  34. else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
  35. var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
  36. safe_add(safe_add(e, w[j]), sha1_kt(j)));
  37. e = d;
  38. d = c;
  39. c = rol(b, 30);
  40. b = a;
  41. a = t;
  42. }
  43. a = safe_add(a, olda);
  44. b = safe_add(b, oldb);
  45. c = safe_add(c, oldc);
  46. d = safe_add(d, oldd);
  47. e = safe_add(e, olde);
  48. }
  49. return Array(a, b, c, d, e);
  50. }
  51. /*
  52. * Perform the appropriate triplet combination function for the current
  53. * iteration
  54. */
  55. function sha1_ft(t, b, c, d)
  56. {
  57. if(t < 20) return (b & c) | ((~b) & d);
  58. if(t < 40) return b ^ c ^ d;
  59. if(t < 60) return (b & c) | (b & d) | (c & d);
  60. return b ^ c ^ d;
  61. }
  62. /*
  63. * Determine the appropriate additive constant for the current iteration
  64. */
  65. function sha1_kt(t)
  66. {
  67. return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 :
  68. (t < 60) ? -1894007588 : -899497514;
  69. }
  70. /*
  71. * Add integers, wrapping at 2^32. This uses 16-bit operations internally
  72. * to work around bugs in some JS interpreters.
  73. */
  74. function safe_add(x, y)
  75. {
  76. var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  77. var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  78. return (msw << 16) | (lsw & 0xFFFF);
  79. }
  80. /*
  81. * Bitwise rotate a 32-bit number to the left.
  82. */
  83. function rol(num, cnt)
  84. {
  85. return (num << cnt) | (num >>> (32 - cnt));
  86. }
  87. module.exports = function sha1(buf) {
  88. return helpers.hash(buf, core_sha1, 20, true);
  89. };