sha1.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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 inherits = require('inherits')
  10. var Hash = require('./hash')
  11. var K = [
  12. 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
  13. ]
  14. var W = new Array(80)
  15. function Sha1 () {
  16. this.init()
  17. this._w = W
  18. Hash.call(this, 64, 56)
  19. }
  20. inherits(Sha1, Hash)
  21. Sha1.prototype.init = function () {
  22. this._a = 0x67452301
  23. this._b = 0xefcdab89
  24. this._c = 0x98badcfe
  25. this._d = 0x10325476
  26. this._e = 0xc3d2e1f0
  27. return this
  28. }
  29. function rotl1 (num) {
  30. return (num << 1) | (num >>> 31)
  31. }
  32. function rotl5 (num) {
  33. return (num << 5) | (num >>> 27)
  34. }
  35. function rotl30 (num) {
  36. return (num << 30) | (num >>> 2)
  37. }
  38. function ft (s, b, c, d) {
  39. if (s === 0) return (b & c) | ((~b) & d)
  40. if (s === 2) return (b & c) | (b & d) | (c & d)
  41. return b ^ c ^ d
  42. }
  43. Sha1.prototype._update = function (M) {
  44. var W = this._w
  45. var a = this._a | 0
  46. var b = this._b | 0
  47. var c = this._c | 0
  48. var d = this._d | 0
  49. var e = this._e | 0
  50. for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
  51. for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16])
  52. for (var j = 0; j < 80; ++j) {
  53. var s = ~~(j / 20)
  54. var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
  55. e = d
  56. d = c
  57. c = rotl30(b)
  58. b = a
  59. a = t
  60. }
  61. this._a = (a + this._a) | 0
  62. this._b = (b + this._b) | 0
  63. this._c = (c + this._c) | 0
  64. this._d = (d + this._d) | 0
  65. this._e = (e + this._e) | 0
  66. }
  67. Sha1.prototype._hash = function () {
  68. var H = new Buffer(20)
  69. H.writeInt32BE(this._a | 0, 0)
  70. H.writeInt32BE(this._b | 0, 4)
  71. H.writeInt32BE(this._c | 0, 8)
  72. H.writeInt32BE(this._d | 0, 12)
  73. H.writeInt32BE(this._e | 0, 16)
  74. return H
  75. }
  76. module.exports = Sha1