-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
EncryptedStorage.js
229 lines (203 loc) · 7.07 KB
/
EncryptedStorage.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
let JSONdb = require('simple-json-db');
let crypto = require('crypto');
const { pbkdf2: deriveKey } = require("pbkdf2");
const events = require('events');
const util = require('util');
const fs = require("fs");
const DERIVATION_ROUNDS = 200000;
const HMAC_KEY_SIZE = 32;
const PASSWORD_KEY_SIZE = 32;
const defaultOptions = {
asyncWrite: false,
syncOnWrite: true,
jsonSpaces: 4,
stringify: JSON.stringify,
parse: JSON.parse
};
function pbkdf2(password, salt, rounds, bits) {
return new Promise((resolve, reject) => {
deriveKey(password, salt, rounds, bits / 8, "sha256", (err, key) => {
if (err) {
return reject(err);
}
return resolve(key);
});
});
}
async function deriveFromPassword(password, salt, rounds) {
if (!password) {
throw new Error("Failed deriving key: Password must be provided");
}
if (!salt) {
throw new Error("Failed deriving key: Salt must be provided");
}
if (!rounds || rounds <= 0 || typeof rounds !== "number") {
throw new Error("Failed deriving key: Rounds must be greater than 0");
}
const bits = (PASSWORD_KEY_SIZE + HMAC_KEY_SIZE) * 8;
const derivedKeyData = await pbkdf2(password, salt, rounds, bits);
const derivedKeyHex = derivedKeyData.toString("hex");
return Buffer.from(derivedKeyHex.substr(0, derivedKeyHex.length / 2), "hex");
}
function generateSalt(length) {
if (length <= 0) {
throw new Error(`Failed generating salt: Invalid length supplied: ${length}`);
}
let output = "";
while (output.length < length) {
output += crypto.randomBytes(3).toString("base64");
if (output.length > length) {
output = output.substr(0, length);
}
}
return output;
}
function validateJSON(fileContent) {
try {
JSON.parse(fileContent);
} catch (e) {
throw new Error('Given filePath is not empty and its content is not valid JSON.');
}
return true;
};
class EncryptedStorage {
/**
* Main constructor, manages existing storage file and parses options against default ones.
* @param {string} filePath The path of the file to use as storage.
* @param {string} iv Encryption initialization vector
* @param {string} salt Password salt used to derive the key
* @param {string} password Encryption password
* @param {object} [options] Configuration options.
* @param {boolean} [options.asyncWrite] Enables the storage to be asynchronously written to disk. Disabled by default (synchronous behaviour).
* @param {boolean} [options.syncOnWrite] Makes the storage be written to disk after every modification. Enabled by default.
* @param {boolean} [options.syncOnWrite] Makes the storage be written to disk after every modification. Enabled by default.
* @param {number} [options.jsonSpaces] How many spaces to use for indentation in the output json files. Default = 4
* @param {object} [options.newData] Data that will be encrypted for the first time
* @constructor
*/
constructor(filePath, password, options) {
// Mandatory arguments check
if (!filePath || !filePath.length) {
throw new Error('Missing file path argument.');
} else {
this.filePath = filePath;
}
// Options parsing
if (options) {
for (let key in defaultOptions) {
if (!options.hasOwnProperty(key)) options[key] = defaultOptions[key];
}
this.options = options;
} else {
this.options = defaultOptions;
}
this.storage = {};
if (!this.options.newData) {
// File existence check
let stats;
try {
stats = fs.statSync(filePath);
} catch (err) {
if (err.code === 'ENOENT') {
/* File doesn't exist */
this.iv = crypto.randomBytes(16).toString('hex');
this.salt = generateSalt(12);
deriveFromPassword(password, this.salt, DERIVATION_ROUNDS).then(derivedKey => {
try {
this.derivedKey = derivedKey;
this.sync();
this.emit('loaded');
} catch (error) {
this.emit('error', error);
}
});
return;
} else if (err.code === 'EACCES') {
throw new Error(`Cannot access path "${filePath}".`);
} else {
// Other error
throw new Error(`Error while checking for existence of path "${filePath}": ${err}`);
}
}
/* File exists */
try {
fs.accessSync(filePath, fs.constants.R_OK | fs.constants.W_OK);
} catch (err) {
throw new Error(`Cannot read & write on path "${filePath}". Check permissions!`);
}
if (stats.size > 0) {
let data;
try {
data = fs.readFileSync(filePath);
} catch (err) {
throw err;
}
if (validateJSON(data)) {
const input_data = JSON.parse(data);
if (!input_data.iv || !input_data.salt || !input_data.data) {
throw new Error('Invalid file');
}
this.iv = input_data.iv;
this.salt = input_data.salt;
deriveFromPassword(password, this.salt, DERIVATION_ROUNDS).then(derivedKey => {
try {
this.derivedKey = derivedKey;
const decryptTool = crypto.createDecipheriv("aes-256-cbc", this.derivedKey, Buffer.from(this.iv, 'hex'));
let decryptedData = decryptTool.update(input_data.data, "base64", "utf8");
decryptedData += decryptTool.final("utf8");
if (validateJSON(decryptedData)) {
this.storage = JSON.parse(decryptedData);
}
this.emit('loaded');
} catch (error) {
this.emit('error', error);
}
});
}
}
}
else {
this.iv = crypto.randomBytes(16).toString('hex');
this.salt = generateSalt(12);
deriveFromPassword(password, this.salt, DERIVATION_ROUNDS).then(derivedKey => {
try {
this.derivedKey = derivedKey;
this.storage = options.newData;
this.sync();
this.emit('loaded');
} catch (error) {
this.emit('error', error);
}
});
}
}
sync() {
const json = JSON.stringify(this.storage, null, this.options.jsonSpaces);
const encryptTool = crypto.createCipheriv("aes-256-cbc", this.derivedKey, Buffer.from(this.iv, 'hex'));
let encryptedData = encryptTool.update(json, "utf8", "base64");
encryptedData += encryptTool.final("base64");
const finalJson = JSON.stringify({
iv: this.iv,
salt: this.salt,
data: encryptedData
})
if (this.options && this.options.asyncWrite) {
fs.writeFile(this.filePath, finalJson, (err) => {
if (err) throw err;
});
} else {
try {
fs.writeFileSync(this.filePath, finalJson);
} catch (err) {
if (err.code === 'EACCES') {
throw new Error(`Cannot access path "${this.filePath}".`);
} else {
throw new Error(`Error while writing to path "${this.filePath}": ${err}`);
}
}
}
}
}
util.inherits(JSONdb, events.EventEmitter);
util.inherits(EncryptedStorage, JSONdb);
module.exports = EncryptedStorage;