copay/js/plugins/EncryptedLocalStorage.js

78 lines
2.1 KiB
JavaScript
Raw Normal View History

2014-10-27 06:36:17 -07:00
var cryptoUtil = require('../util/crypto');
2014-12-02 06:17:03 -08:00
var log = require('../util/log');
2014-10-27 06:36:17 -07:00
var LocalStorage = require('./LocalStorage');
var inherits = require('inherits');
2014-12-13 15:06:16 -08:00
var preconditions = require('preconditions').singleton();
2014-10-27 06:36:17 -07:00
2014-11-10 20:23:12 -08:00
var SEPARATOR = '@#$';
2014-10-27 06:36:17 -07:00
function EncryptedLocalStorage(config) {
LocalStorage.apply(this, [config]);
}
inherits(EncryptedLocalStorage, LocalStorage);
2014-11-10 17:58:46 -08:00
EncryptedLocalStorage.prototype._brokenDecrypt = function(body) {
var key = cryptoUtil.kdf(this.password + this.email, 'mjuBtGybi/4=', 100);
log.debug('Trying legacy decrypt')
var decryptedJson = cryptoUtil.decrypt(key, body);
return decryptedJson;
};
2014-12-13 14:47:24 -08:00
EncryptedLocalStorage.prototype._brokenDecryptUndef = function(body) {
var badkey = undefined + SEPARATOR + undefined;
return cryptoUtil.decrypt(badkey, body);
};
2014-10-27 06:36:17 -07:00
EncryptedLocalStorage.prototype.getItem = function(name, callback) {
2014-11-10 18:08:14 -08:00
var self = this;
2014-12-13 15:06:16 -08:00
preconditions.checkState(self.email);
LocalStorage.prototype.getItem.apply(this, [name,
function(err, body) {
2014-12-13 15:06:16 -08:00
2014-11-10 20:23:12 -08:00
var decryptedJson = cryptoUtil.decrypt(self.email + SEPARATOR + self.password, body);
if (!decryptedJson) {
2014-11-10 18:08:14 -08:00
log.debug('Could not decrypt value using current decryption schema');
decryptedJson = self._brokenDecrypt(body);
2014-11-10 17:58:46 -08:00
}
2014-12-13 14:47:24 -08:00
if (!decryptedJson) {
decryptedJson = self._brokenDecryptUndef(body);
}
2014-11-10 17:58:46 -08:00
if (!decryptedJson) {
log.debug('Could not decrypt value.');
return callback('PNOTFOUND');
}
2014-11-10 17:58:46 -08:00
return callback(null, decryptedJson);
2014-10-27 06:36:17 -07:00
}
]);
2014-10-27 06:36:17 -07:00
};
EncryptedLocalStorage.prototype.setItem = function(name, value, callback) {
if (!_.isString(value)) {
value = JSON.stringify(value);
}
2014-11-10 20:23:12 -08:00
var record = cryptoUtil.encrypt(this.email + SEPARATOR + this.password, value);
2014-10-27 06:36:17 -07:00
LocalStorage.prototype.setItem.apply(this, [name, record, callback]);
};
2014-11-10 17:58:46 -08:00
EncryptedLocalStorage.prototype.removeItem = function(name, callback) {
LocalStorage.prototype.removeItem.apply(this, [name, callback]);
2014-11-10 17:58:46 -08:00
};
EncryptedLocalStorage.prototype.clear = function(callback) {
LocalStorage.prototype.clear.apply(this, [callback]);
};
2014-11-10 17:58:46 -08:00
2014-10-27 06:36:17 -07:00
module.exports = EncryptedLocalStorage;