sha1.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. (function() {
  2. var crypt = require('crypt'),
  3. utf8 = require('charenc').utf8,
  4. bin = require('charenc').bin,
  5. // The core
  6. sha1 = function (message) {
  7. // Convert to byte array
  8. if (message.constructor == String)
  9. message = utf8.stringToBytes(message);
  10. else if (typeof Buffer !== 'undefined' && typeof Buffer.isBuffer == 'function' && Buffer.isBuffer(message))
  11. message = Array.prototype.slice.call(message, 0);
  12. else if (!Array.isArray(message))
  13. message = message.toString();
  14. // otherwise assume byte array
  15. var m = crypt.bytesToWords(message),
  16. l = message.length * 8,
  17. w = [],
  18. H0 = 1732584193,
  19. H1 = -271733879,
  20. H2 = -1732584194,
  21. H3 = 271733878,
  22. H4 = -1009589776;
  23. // Padding
  24. m[l >> 5] |= 0x80 << (24 - l % 32);
  25. m[((l + 64 >>> 9) << 4) + 15] = l;
  26. for (var i = 0; i < m.length; i += 16) {
  27. var a = H0,
  28. b = H1,
  29. c = H2,
  30. d = H3,
  31. e = H4;
  32. for (var j = 0; j < 80; j++) {
  33. if (j < 16)
  34. w[j] = m[i + j];
  35. else {
  36. var n = w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16];
  37. w[j] = (n << 1) | (n >>> 31);
  38. }
  39. var t = ((H0 << 5) | (H0 >>> 27)) + H4 + (w[j] >>> 0) + (
  40. j < 20 ? (H1 & H2 | ~H1 & H3) + 1518500249 :
  41. j < 40 ? (H1 ^ H2 ^ H3) + 1859775393 :
  42. j < 60 ? (H1 & H2 | H1 & H3 | H2 & H3) - 1894007588 :
  43. (H1 ^ H2 ^ H3) - 899497514);
  44. H4 = H3;
  45. H3 = H2;
  46. H2 = (H1 << 30) | (H1 >>> 2);
  47. H1 = H0;
  48. H0 = t;
  49. }
  50. H0 += a;
  51. H1 += b;
  52. H2 += c;
  53. H3 += d;
  54. H4 += e;
  55. }
  56. return [H0, H1, H2, H3, H4];
  57. },
  58. // Public API
  59. api = function (message, options) {
  60. var digestbytes = crypt.wordsToBytes(sha1(message));
  61. return options && options.asBytes ? digestbytes :
  62. options && options.asString ? bin.bytesToString(digestbytes) :
  63. crypt.bytesToHex(digestbytes);
  64. };
  65. api._blocksize = 16;
  66. api._digestsize = 20;
  67. module.exports = api;
  68. })();