-
Notifications
You must be signed in to change notification settings - Fork 801
/
encryption.js
398 lines (342 loc) · 11.5 KB
/
encryption.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
/**
* Copyright (C) 2015 Laverna project Authors.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/* global define */
define([
'q',
'underscore',
'marionette',
'backbone.radio',
'classes/sjcl.worker',
'sjcl'
], function(Q, _, Marionette, Radio, Sjcl, sjcl) {
'use strict';
/**
* Encryption class.
*
* Replies to requests on channel `encrypt`:
* 1. `sha256` - generates and returns sha256 hash of provided string.
* 2. `randomize` - generates and returns random data.
* 3. `change:configs` - changes encryption configs.
* 4. `delete:secureKey` - delete PBKDF2 from session storage.
*
* 3. `check:auth` - checks whether a user is authorized.
* 4. `check:password` - validate provided password.
* 5. `save:secureKey` - compute PBKDF2 and save it to session storage.
*
* 6. `encrypt` - encrypt a string
* 7. `decrypt` - decrypt a string
* 8. `encrypt:model` - encrypt a Backbone model
* 9. `decrypt:model` - decrypt a Backbone model
* 10. `encrypt:models` - encrypt a Backbone collection
* 11. `decrypt:models` - decrypt a Backbone collection
*/
var Encrypt = Marionette.Object.extend({
initialize: function() {
// Get configs
this.configs = Radio.request('configs', 'get:object');
this.keys = {};
this.sjcl = new Sjcl(this.configs);
// Pass requests directly to Sjcl class
Radio.reply('encrypt', {
'sha256' : this.sjcl.sha256,
}, this.sjcl);
// Replies
Radio.reply('encrypt', {
'randomize' : this.randomize,
'change:configs' : this.changeConfigs,
// Check auth/password
'check:auth' : this.checkAuth,
'check:password' : this.checkPassword,
'save:secureKey' : this.saveSecureKey,
'delete:secureKey' : this.deleteSecureKey,
// Encrypt/decrypt some string
'encrypt' : this.encrypt,
'decrypt' : this.decrypt,
// Encrypt/decrypt a model
'encrypt:model' : this.encryptModel,
'decrypt:model' : this.decryptModel,
// Encrypt/decrypt a collection of models
'encrypt:models' : this.encryptModels,
'decrypt:models' : this.decryptModels
}, this);
},
/**
* Generate random words.
*
* @return string
*/
randomize: function(number, paranoia, noHex) {
if (noHex) {
return sjcl.random.randomWords(number, paranoia);
}
return sjcl.codec.hex.fromBits(
sjcl.random.randomWords(number, paranoia)
);
},
/**
* Change encryption configs. It is useful when re-encrypting data.
*/
changeConfigs: function(configs) {
configs = configs || Radio.request('configs', 'get:object');
this.configs = _.extend(this.configs, configs);
},
/**
* Check whether a user is already authorized
*
* @return bool
*/
checkAuth: function() {
/**
* If encryption backup is not empty, it means a user changed
* encryption settings.
*/
if (!_.isEmpty(this.configs.encryptBackup)) {
Radio.trigger('encrypt', 'changed');
return {isChanged: true};
}
// Encryption is disabled
if (!Number(this.configs.encrypt) || this.configs.encryptPass === '') {
return true;
}
return !_.isEmpty(this.keys) || this._getSession() !== null;
},
/**
* Check the password with the password in the database which is saved
* in there in sha256 hash format. Note, just the password is not used
* for encrypting/decrypting data. We use instead PBKDF2.
*
* @return promise
*/
checkPassword: function(password) {
var pwd = this.configs.encryptPass;
return new Q(this.sjcl.sha256(password))
.then(function(hash) {
return hash.toString() === pwd.toString();
});
},
/**
* Generate PBKDF2 and save it. It will be used to encrypt/decrypt data.
*
* @return promise
*/
saveSecureKey: function(password) {
var self = this;
return new Q(this.sjcl.deriveKey({
configs : this.configs,
password: password
}))
.then(function(keys) {
self.keys.key = keys.key;
self.keys.hexKey = keys.hexKey;
self._saveSession();
});
},
/**
* Delete current PBKDF2.
*/
deleteSecureKey: function() {
this.keys = {};
if (window.sessionStorage) {
window.sessionStorage.removeItem(this._getSessionKey());
}
},
/**
* Encrypt data.
*
* @return promise
*/
encrypt: function(str) {
return new Q(this.sjcl.encrypt({
configs : this.configs,
string : str,
keys : this.keys,
// Random initialization vector every time
iv : sjcl.random.randomWords(4, 0),
}));
},
/**
* Decrypt data.
*
* @return promise
*/
decrypt: function(str) {
return new Q(this.sjcl.decrypt({
configs : this.configs,
string : str,
keys : this.keys,
}));
},
/**
* Encrypt a model.
*
* @return promise
*/
encryptModel: function(model) {
var data = _.pick(model.attributes, model.encryptKeys);
return this.encrypt(data)
.then(function(encrypted) {
model.set('encryptedData', encrypted);
return model;
});
},
/**
* Decrypt a model.
*
* @return promise
*/
decryptModel: function(model) {
if (model.attributes.encryptedData) {
return this._decryptModel(model);
}
return this._decryptModelKeys(model);
},
/**
* Encrypt a collection.
*
* @return promise
*/
encryptModels: function(collection) {
// The collection is empty or PBKDF2 wasn't generated
if (!collection.length || !Number(this.configs.encrypt) ||
!this.keys.key) {
return new Q();
}
var promises = [],
self = this;
Radio.trigger('encrypt', 'encrypting:models', collection);
collection.each(function(model) {
promises.push(function() {
return new Q(self.encryptModel(model));
});
}, this);
return _.reduce(promises, Q.when, new Q())
.fail(function(e) {
console.error('EncryptModels Error:', e);
});
},
/**
* Decrypt a collection.
*
* @return promise
*/
decryptModels: function(collection) {
// The collection is empty or encryption is disabled
if (!collection.length || !Number(this.configs.encrypt)) {
return new Q();
}
// PBKDF2 wasn't generated
if (!this.keys.key) {
Radio.trigger('encrypt', 'decrypt:error', 'PBKDF2 is empty');
return new Q();
}
var promises = [],
self = this;
Radio.trigger('encrypt', 'decrypting:models', collection);
collection.each(function(model) {
promises.push(function() {
return new Q(self.decryptModel(model));
});
}, this);
return _.reduce(promises, Q.when, new Q())
.fail(function(e) {
console.error('DecryptModels Error:', e);
});
},
/**
* Decrypt a model by getting data from "encryptedData" attribute.
*
* @return promise
*/
_decryptModel: function(model) {
return new Q(this.sjcl.decrypt({
configs : this.configs,
string : model.get('encryptedData'),
keys : this.keys,
}))
.then(function(data) {
_.each(JSON.parse(data), function(val, key) {
model.set(key, val);
});
Radio.trigger('encrypt', 'decrypted:model', model);
return model;
});
},
/**
* Deprecated decryption.
*
* @return promise
*/
_decryptModelKeys: function(model) {
var promises = [],
self = this;
_.each(model.encryptKeys, function(key) {
promises.push(
new Q(self.sjcl.decryptLegacy({
configs : self.configs,
string : model.get(key),
keys : this.keys
}))
.then(function(data) {
model.set(key, data);
})
);
}, this);
return Q.all(promises)
.then(function() {
Radio.trigger('encrypt', 'decrypted:model', model);
return model;
});
},
/**
* Save PBKDF2 to sessionStorage. That way the user will not have to
* type their passwords every time.
*/
_saveSession: function() {
if (!window.sessionStorage || !this.keys) {
return;
}
window.sessionStorage.setItem(
this._getSessionKey(),
JSON.stringify(this.keys)
);
},
/**
* Get PBKDF2 from sessionStorage.
*
* @return [object|null]
*/
_getSession: function() {
if (!window.sessionStorage) {
return null;
}
var keys = window.sessionStorage.getItem(this._getSessionKey());
try {
keys = JSON.parse(keys);
this.keys = keys || this.keys;
} catch (e) {
keys = null;
}
return keys;
},
/**
* Return session storage key which will be used to save PBKDF2.
*
* @return string
*/
_getSessionKey: function() {
var profile = Radio.request('uri', 'profile') || 'default';
profile = (Number(this.configs.useDefaultConfigs) ? 'default' : profile);
return 'secureKey.' + profile;
}
});
// Initialize
Radio.request('init', 'add', 'app:before', function() {
new Encrypt();
});
return Encrypt;
});