Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80542 views
1
'use strict';
2
var inherits = require('inherits')
3
var md5 = require('./md5')
4
var rmd160 = require('ripemd160')
5
var sha = require('sha.js')
6
7
var Transform = require('stream').Transform
8
9
function HashNoConstructor(hash) {
10
Transform.call(this)
11
12
this._hash = hash
13
this.buffers = []
14
}
15
16
inherits(HashNoConstructor, Transform)
17
18
HashNoConstructor.prototype._transform = function (data, _, next) {
19
this.buffers.push(data)
20
21
next()
22
}
23
24
HashNoConstructor.prototype._flush = function (next) {
25
this.push(this.digest())
26
next()
27
}
28
29
HashNoConstructor.prototype.update = function (data, enc) {
30
if (typeof data === 'string') {
31
data = new Buffer(data, enc)
32
}
33
34
this.buffers.push(data)
35
return this
36
}
37
38
HashNoConstructor.prototype.digest = function (enc) {
39
var buf = Buffer.concat(this.buffers)
40
var r = this._hash(buf)
41
this.buffers = null
42
43
return enc ? r.toString(enc) : r
44
}
45
46
function Hash(hash) {
47
Transform.call(this)
48
49
this._hash = hash
50
}
51
52
inherits(Hash, Transform)
53
54
Hash.prototype._transform = function (data, enc, next) {
55
if (enc) data = new Buffer(data, enc)
56
57
this._hash.update(data)
58
59
next()
60
}
61
62
Hash.prototype._flush = function (next) {
63
this.push(this._hash.digest())
64
this._hash = null
65
66
next()
67
}
68
69
Hash.prototype.update = function (data, enc) {
70
if (typeof data === 'string') {
71
data = new Buffer(data, enc)
72
}
73
74
this._hash.update(data)
75
return this
76
}
77
78
Hash.prototype.digest = function (enc) {
79
var outData = this._hash.digest()
80
81
return enc ? outData.toString(enc) : outData
82
}
83
84
module.exports = function createHash (alg) {
85
if ('md5' === alg) return new HashNoConstructor(md5)
86
if ('rmd160' === alg) return new HashNoConstructor(rmd160)
87
88
return new Hash(sha(alg))
89
}
90
91