-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.js
112 lines (93 loc) · 2.37 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/**
* This file contains a modified copy of LazyTransform and Hash
* from io.js/lib/crypto.js
*/
"use strict";
const stream = require('stream');
const binding = require('./build/Release/blake2');
class LazyTransform extends stream.Transform {
constructor(options) {
super();
this._options = options;
}
}
[
'_readableState',
'_writableState',
'_transformState'
].forEach(function(prop) {
Object.defineProperty(LazyTransform.prototype, prop, {
get: function() {
stream.Transform.call(this, this._options);
this._writableState.decodeStrings = false;
this._writableState.defaultEncoding = 'binary';
return this[prop];
},
set: function(val) {
Object.defineProperty(this, prop, {
value: val,
enumerable: true,
configurable: true,
writable: true
});
},
configurable: true,
enumerable: true
});
});
class Hash extends LazyTransform {
constructor(algorithm, options) {
super(options);
let digestLength = -1;
if (options && 'digestLength' in options) {
digestLength = options.digestLength;
}
this._handle = new binding.Hash(algorithm, null, digestLength);
}
_transform(chunk, encoding, callback) {
this._handle.update(chunk, encoding);
callback();
}
_flush(callback) {
this.push(this._handle.digest());
callback();
}
update(buf) {
this._handle.update(buf);
return this;
}
digest(outputEncoding) {
const buf = this._handle.digest();
if(outputEncoding) {
return buf.toString(outputEncoding);
}
return buf;
}
copy() {
const h = new this.constructor("bypass");
h._handle = this._handle.copy();
return h;
}
}
function createHash(algorithm, options) {
return new Hash(algorithm, options);
}
class KeyedHash extends LazyTransform {
constructor(algorithm, key, options) {
super(options);
let digestLength = -1;
if (options && 'digestLength' in options) {
digestLength = options.digestLength;
}
this._handle = new binding.Hash(algorithm, key, digestLength);
}
}
KeyedHash.prototype.update = Hash.prototype.update;
KeyedHash.prototype.digest = Hash.prototype.digest;
KeyedHash.prototype.copy = Hash.prototype.copy;
KeyedHash.prototype._flush = Hash.prototype._flush;
KeyedHash.prototype._transform = Hash.prototype._transform;
function createKeyedHash(algorithm, key, options) {
return new KeyedHash(algorithm, key, options);
}
module.exports = {Hash, createHash, KeyedHash, createKeyedHash};