|
| 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 | + |
| 9 | +var inherits = require('inherits') |
| 10 | +var Hash = require('./hash') |
| 11 | + |
| 12 | +var W = new Array(80) |
| 13 | + |
| 14 | +function Sha() { |
| 15 | + this.init() |
| 16 | + this._w = W |
| 17 | + |
| 18 | + Hash.call(this, 64, 56) |
| 19 | +} |
| 20 | + |
| 21 | +inherits(Sha, Hash) |
| 22 | + |
| 23 | +Sha.prototype.init = function () { |
| 24 | + this._a = 0x67452301 |
| 25 | + this._b = 0xefcdab89 |
| 26 | + this._c = 0x98badcfe |
| 27 | + this._d = 0x10325476 |
| 28 | + this._e = 0xc3d2e1f0 |
| 29 | + |
| 30 | + return this |
| 31 | +} |
| 32 | + |
| 33 | +/* |
| 34 | + * Bitwise rotate a 32-bit number to the left. |
| 35 | + */ |
| 36 | +function rol(num, cnt) { |
| 37 | + return (num << cnt) | (num >>> (32 - cnt)); |
| 38 | +} |
| 39 | + |
| 40 | +Sha.prototype._update = function (M) { |
| 41 | + var W = this._w |
| 42 | + |
| 43 | + var a = this._a |
| 44 | + var b = this._b |
| 45 | + var c = this._c |
| 46 | + var d = this._d |
| 47 | + var e = this._e |
| 48 | + |
| 49 | + var j = 0, k |
| 50 | + |
| 51 | + /* |
| 52 | + * SHA-1 has a bitwise rotate left operation. But, SHA is not |
| 53 | + * function calcW() { return rol(W[j - 3] ^ W[j - 8] ^ W[j - 14] ^ W[j - 16], 1) } |
| 54 | + */ |
| 55 | + function calcW() { return W[j - 3] ^ W[j - 8] ^ W[j - 14] ^ W[j - 16] } |
| 56 | + function loop(w, f) { |
| 57 | + W[j] = w |
| 58 | + |
| 59 | + var t = rol(a, 5) + f + e + w + k |
| 60 | + |
| 61 | + e = d |
| 62 | + d = c |
| 63 | + c = rol(b, 30) |
| 64 | + b = a |
| 65 | + a = t |
| 66 | + j++ |
| 67 | + } |
| 68 | + |
| 69 | + k = 1518500249 |
| 70 | + while (j < 16) loop(M.readInt32BE(j * 4), (b & c) | ((~b) & d)) |
| 71 | + while (j < 20) loop(calcW(), (b & c) | ((~b) & d)) |
| 72 | + k = 1859775393 |
| 73 | + while (j < 40) loop(calcW(), b ^ c ^ d) |
| 74 | + k = -1894007588 |
| 75 | + while (j < 60) loop(calcW(), (b & c) | (b & d) | (c & d)) |
| 76 | + k = -899497514 |
| 77 | + while (j < 80) loop(calcW(), b ^ c ^ d) |
| 78 | + |
| 79 | + this._a = (a + this._a) | 0 |
| 80 | + this._b = (b + this._b) | 0 |
| 81 | + this._c = (c + this._c) | 0 |
| 82 | + this._d = (d + this._d) | 0 |
| 83 | + this._e = (e + this._e) | 0 |
| 84 | +} |
| 85 | + |
| 86 | +Sha.prototype._hash = function () { |
| 87 | + var H = new Buffer(20) |
| 88 | + |
| 89 | + H.writeInt32BE(this._a|0, 0) |
| 90 | + H.writeInt32BE(this._b|0, 4) |
| 91 | + H.writeInt32BE(this._c|0, 8) |
| 92 | + H.writeInt32BE(this._d|0, 12) |
| 93 | + H.writeInt32BE(this._e|0, 16) |
| 94 | + |
| 95 | + return H |
| 96 | +} |
| 97 | + |
| 98 | +module.exports = Sha |
| 99 | + |
0 commit comments