UNPKG

whstorage

Version:

whSotorage is a way to encrypt localSotage

75 lines (53 loc) 2.06 kB
const sjcl = require('../deps/sjcl') if(typeof sjcl === 'undefined') { throw new Error("SJCL Encrypter lib is required!!! Download at: http://bitwiseshiftleft.github.io/sjcl/sjcl.js") } const whStorage = {}; whStorage.getPrimary = function() { var val = JSON.parse(localStorage.getItem('whs_data')) return val }; whStorage.options = { key: (localStorage.length) ? whStorage.getPrimary().primary : '', prefix: (localStorage.length) ? whStorage.getPrimary().secondary : '' }; whStorage.set = function(section, item) { var data = whStorage.encrypte(whStorage.getOptions().key, JSON.stringify(item)); return localStorage.setItem(whStorage.defineSection(section), data); }; whStorage.defineSection = function(section) { return whStorage.getOptions().prefix.concat(section) }; whStorage.get = function(item){ return JSON.parse(whStorage.decrypte(whStorage.getOptions().key, localStorage.getItem(whStorage.defineSection(item)))) }; whStorage.claer = function() {localStorage.clear()}; whStorage.init = function(options) { this.key = options.key this.prefix = options.prefix if(this.key === undefined){ throw new Error('whStorageErr: Crypting key not found!') } const data = { primary: this.key, secondary: this.prefix } if(options.key !== undefined) whStorage.options.key = this.key if(options.prefix !== undefined) whStorage.options.prefix = this.prefix localStorage.setItem('whs_data', JSON.stringify(data)); }; whStorage.getOptions = function(){ if(whStorage.options.prefix !== undefined || whStorage.options.prefix !== null) return whStorage.options return whStorage.options.key }; whStorage.encrypte = function(password, data){ if(password !== undefined) return sjcl.encrypt(password, data); }; whStorage.decrypte = function(password, encryptedData){ return sjcl.decrypt(password, encryptedData); }; module.exports = whStorage;