sha.js 1.9 KB

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