1
|
var Buffer = require('safe-buffer').Buffer
|
2
|
|
3
|
// prototype class for hash functions
|
4
|
function Hash (blockSize, finalSize) {
|
5
|
this._block = Buffer.alloc(blockSize)
|
6
|
this._finalSize = finalSize
|
7
|
this._blockSize = blockSize
|
8
|
this._len = 0
|
9
|
}
|
10
|
|
11
|
Hash.prototype.update = function (data, enc) {
|
12
|
if (typeof data === 'string') {
|
13
|
enc = enc || 'utf8'
|
14
|
data = Buffer.from(data, enc)
|
15
|
}
|
16
|
|
17
|
var block = this._block
|
18
|
var blockSize = this._blockSize
|
19
|
var length = data.length
|
20
|
var accum = this._len
|
21
|
|
22
|
for (var offset = 0; offset < length;) {
|
23
|
var assigned = accum % blockSize
|
24
|
var remainder = Math.min(length - offset, blockSize - assigned)
|
25
|
|
26
|
for (var i = 0; i < remainder; i++) {
|
27
|
block[assigned + i] = data[offset + i]
|
28
|
}
|
29
|
|
30
|
accum += remainder
|
31
|
offset += remainder
|
32
|
|
33
|
if ((accum % blockSize) === 0) {
|
34
|
this._update(block)
|
35
|
}
|
36
|
}
|
37
|
|
38
|
this._len += length
|
39
|
return this
|
40
|
}
|
41
|
|
42
|
Hash.prototype.digest = function (enc) {
|
43
|
var rem = this._len % this._blockSize
|
44
|
|
45
|
this._block[rem] = 0x80
|
46
|
|
47
|
// zero (rem + 1) trailing bits, where (rem + 1) is the smallest
|
48
|
// non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize
|
49
|
this._block.fill(0, rem + 1)
|
50
|
|
51
|
if (rem >= this._finalSize) {
|
52
|
this._update(this._block)
|
53
|
this._block.fill(0)
|
54
|
}
|
55
|
|
56
|
var bits = this._len * 8
|
57
|
|
58
|
// uint32
|
59
|
if (bits <= 0xffffffff) {
|
60
|
this._block.writeUInt32BE(bits, this._blockSize - 4)
|
61
|
|
62
|
// uint64
|
63
|
} else {
|
64
|
var lowBits = (bits & 0xffffffff) >>> 0
|
65
|
var highBits = (bits - lowBits) / 0x100000000
|
66
|
|
67
|
this._block.writeUInt32BE(highBits, this._blockSize - 8)
|
68
|
this._block.writeUInt32BE(lowBits, this._blockSize - 4)
|
69
|
}
|
70
|
|
71
|
this._update(this._block)
|
72
|
var hash = this._hash()
|
73
|
|
74
|
return enc ? hash.toString(enc) : hash
|
75
|
}
|
76
|
|
77
|
Hash.prototype._update = function () {
|
78
|
throw new Error('_update must be implemented by subclass')
|
79
|
}
|
80
|
|
81
|
module.exports = Hash
|