sha1.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. const Crypto = require('./crypto.js');
  2. (function(){
  3. // Shortcut
  4. var util = Crypto.util;
  5. // Public API
  6. var SHA1 = Crypto.SHA1 = function (message, options) {
  7. var digestbytes = util.wordsToBytes(SHA1._sha1(message));
  8. return options && options.asBytes ? digestbytes :
  9. options && options.asString ? util.bytesToString(digestbytes) :
  10. util.bytesToHex(digestbytes);
  11. };
  12. // The core
  13. SHA1._sha1 = function (message) {
  14. var m = util.stringToWords(message),
  15. l = message.length * 8,
  16. w = [],
  17. H0 = 1732584193,
  18. H1 = -271733879,
  19. H2 = -1732584194,
  20. H3 = 271733878,
  21. H4 = -1009589776;
  22. // Padding
  23. m[l >> 5] |= 0x80 << (24 - l % 32);
  24. m[((l + 64 >>> 9) << 4) + 15] = l;
  25. for (var i = 0; i < m.length; i += 16) {
  26. var a = H0,
  27. b = H1,
  28. c = H2,
  29. d = H3,
  30. e = H4;
  31. for (var j = 0; j < 80; j++) {
  32. if (j < 16) w[j] = m[i + j];
  33. else {
  34. var n = w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16];
  35. w[j] = (n << 1) | (n >>> 31);
  36. }
  37. var t = ((H0 << 5) | (H0 >>> 27)) + H4 + (w[j] >>> 0) + (
  38. j < 20 ? (H1 & H2 | ~H1 & H3) + 1518500249 :
  39. j < 40 ? (H1 ^ H2 ^ H3) + 1859775393 :
  40. j < 60 ? (H1 & H2 | H1 & H3 | H2 & H3) - 1894007588 :
  41. (H1 ^ H2 ^ H3) - 899497514);
  42. H4 = H3;
  43. H3 = H2;
  44. H2 = (H1 << 30) | (H1 >>> 2);
  45. H1 = H0;
  46. H0 = t;
  47. }
  48. H0 += a;
  49. H1 += b;
  50. H2 += c;
  51. H3 += d;
  52. H4 += e;
  53. }
  54. return [H0, H1, H2, H3, H4];
  55. };
  56. // Package private blocksize
  57. SHA1._blocksize = 16;
  58. })();
  59. module.exports = Crypto;