SHA1.js 1.8 KB

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