sha.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
  3. * in FIPS PUB 180-1
  4. * This source code is derived from sha1.js of the same repository.
  5. * The difference between SHA-0 and SHA-1 is just a bitwise rotate left
  6. * operation was added.
  7. */
  8. var inherits = require('inherits')
  9. var Hash = require('./hash')
  10. var K = [
  11. 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
  12. ]
  13. var W = new Array(80)
  14. function Sha () {
  15. this.init()
  16. this._w = W
  17. Hash.call(this, 64, 56)
  18. }
  19. inherits(Sha, Hash)
  20. Sha.prototype.init = function () {
  21. this._a = 0x67452301
  22. this._b = 0xefcdab89
  23. this._c = 0x98badcfe
  24. this._d = 0x10325476
  25. this._e = 0xc3d2e1f0
  26. return this
  27. }
  28. function rotl5 (num) {
  29. return (num << 5) | (num >>> 27)
  30. }
  31. function rotl30 (num) {
  32. return (num << 30) | (num >>> 2)
  33. }
  34. function ft (s, b, c, d) {
  35. if (s === 0) return (b & c) | ((~b) & d)
  36. if (s === 2) return (b & c) | (b & d) | (c & d)
  37. return b ^ c ^ d
  38. }
  39. Sha.prototype._update = function (M) {
  40. var W = this._w
  41. var a = this._a | 0
  42. var b = this._b | 0
  43. var c = this._c | 0
  44. var d = this._d | 0
  45. var e = this._e | 0
  46. for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
  47. for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]
  48. for (var j = 0; j < 80; ++j) {
  49. var s = ~~(j / 20)
  50. var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
  51. e = d
  52. d = c
  53. c = rotl30(b)
  54. b = a
  55. a = t
  56. }
  57. this._a = (a + this._a) | 0
  58. this._b = (b + this._b) | 0
  59. this._c = (c + this._c) | 0
  60. this._d = (d + this._d) | 0
  61. this._e = (e + this._e) | 0
  62. }
  63. Sha.prototype._hash = function () {
  64. var H = new Buffer(20)
  65. H.writeInt32BE(this._a | 0, 0)
  66. H.writeInt32BE(this._b | 0, 4)
  67. H.writeInt32BE(this._c | 0, 8)
  68. H.writeInt32BE(this._d | 0, 12)
  69. H.writeInt32BE(this._e | 0, 16)
  70. return H
  71. }
  72. module.exports = Sha