sha1.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. 'use strict';
  2. /*
  3. * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
  4. * in FIPS PUB 180-1
  5. * Version 2.1a Copyright Paul Johnston 2000 - 2002.
  6. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  7. * Distributed under the BSD License
  8. * See http://pajhome.org.uk/crypt/md5 for details.
  9. */
  10. var inherits = require('inherits');
  11. var Hash = require('./hash');
  12. var Buffer = require('safe-buffer').Buffer;
  13. var K = [
  14. 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
  15. ];
  16. var W = new Array(80);
  17. function Sha1() {
  18. this.init();
  19. this._w = W;
  20. Hash.call(this, 64, 56);
  21. }
  22. inherits(Sha1, Hash);
  23. Sha1.prototype.init = function () {
  24. this._a = 0x67452301;
  25. this._b = 0xefcdab89;
  26. this._c = 0x98badcfe;
  27. this._d = 0x10325476;
  28. this._e = 0xc3d2e1f0;
  29. return this;
  30. };
  31. function rotl1(num) {
  32. return (num << 1) | (num >>> 31);
  33. }
  34. function rotl5(num) {
  35. return (num << 5) | (num >>> 27);
  36. }
  37. function rotl30(num) {
  38. return (num << 30) | (num >>> 2);
  39. }
  40. function ft(s, b, c, d) {
  41. if (s === 0) {
  42. return (b & c) | (~b & d);
  43. }
  44. if (s === 2) {
  45. return (b & c) | (b & d) | (c & d);
  46. }
  47. return b ^ c ^ d;
  48. }
  49. Sha1.prototype._update = function (M) {
  50. var w = this._w;
  51. var a = this._a | 0;
  52. var b = this._b | 0;
  53. var c = this._c | 0;
  54. var d = this._d | 0;
  55. var e = this._e | 0;
  56. for (var i = 0; i < 16; ++i) {
  57. w[i] = M.readInt32BE(i * 4);
  58. }
  59. for (; i < 80; ++i) {
  60. w[i] = rotl1(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);
  61. }
  62. for (var j = 0; j < 80; ++j) {
  63. var s = ~~(j / 20);
  64. var t = (rotl5(a) + ft(s, b, c, d) + e + w[j] + K[s]) | 0;
  65. e = d;
  66. d = c;
  67. c = rotl30(b);
  68. b = a;
  69. a = t;
  70. }
  71. this._a = (a + this._a) | 0;
  72. this._b = (b + this._b) | 0;
  73. this._c = (c + this._c) | 0;
  74. this._d = (d + this._d) | 0;
  75. this._e = (e + this._e) | 0;
  76. };
  77. Sha1.prototype._hash = function () {
  78. var H = Buffer.allocUnsafe(20);
  79. H.writeInt32BE(this._a | 0, 0);
  80. H.writeInt32BE(this._b | 0, 4);
  81. H.writeInt32BE(this._c | 0, 8);
  82. H.writeInt32BE(this._d | 0, 12);
  83. H.writeInt32BE(this._e | 0, 16);
  84. return H;
  85. };
  86. module.exports = Sha1;