Git Product home page Git Product logo

secure-ls's Introduction

secure-ls

Secure localStorage data with high level of encryption and data compression.

npm version npm Build Status Coverage Status

LIVE DEMO

Features

  • Secure data with various types of encryption including AES, DES, Rabbit and RC4. (defaults to Base64 encoding).
  • Compress data before storing it to localStorage to save extra bytes (defaults to true).
  • Advanced API wrapper over localStorage API, providing other basic utilities.
  • Save data in multiple keys inside localStorage and secure-ls will always remember it's creation.

Installation

$ npm install secure-ls

Libraries used

  • Encryption / Decryption using The Cipher Algorithms

    It requires secret-key for encrypting and decrypting data securely. If custom secret-key is provided as mentioned below in APIs, then the library will pick that otherwise it will generate yet another very secure unique password key using PBKDF2, which will be further used for future API requests.

    PBKDF2 is a password-based key derivation function. In many applications of cryptography, user security is ultimately dependent on a password, and because a password usually can't be used directly as a cryptographic key, some processing is required.

    A salt provides a large set of keys for any given password, and an iteration count increases the cost of producing keys from a password, thereby also increasing the difficulty of attack.

    Eg: 55e8f5585789191d350329b9ebcf2b11 and db51d35aad96610683d5a40a70b20c39.

    For the generation of such strings, secretPhrase is being used and can be found in code easily but that won't make it unsecure, PBKDF2's layer on top of that will handle security.

  • Compresion / Decompression using lz-string

Usage

  • Example 1: With default settings i.e. Base64 Encoding and Data Compression
> var ls = new SecureLS();
> ls.set('key1', {data: 'test'}); // set key1
> ls.get('key1'); // print data
  {data: 'test'}
  • Example 2: With AES Encryption and Data Compression
> var ls = new SecureLS({encodingType: 'aes'});
> ls.set('key1', {data: 'test'}); // set key1
> ls.get('key1'); // print data
  {data: 'test'}

> ls.set('key2', [1, 2, 3]); // set another key
> ls.getAllKeys(); // get all keys
  ["key1", "key2"]
> ls.removeAll(); // remove all keys

  • Example 3: With RC4 Encryption but no Data Compression
> var ls = new SecureLS({encodingType: 'rc4', isCompression: false});
> ls.set('key1', {data: 'test'}); // set key1
> ls.get('key1'); // print data
  {data: 'test'}

> ls.set('key2', [1, 2, 3]); // set another key
> ls.getAllKeys(); // get all keys
  ["key1", "key2"]
> ls.removeAll(); // remove all keys

  • Example 3: With DES Encryption, no Data Compression and custom secret key
> var ls = new SecureLS({encodingType: 'des', isCompression: false, encryptionSecret: 'my-secret-key'});
> ls.set('key1', {data: 'test'}); // set key1
> ls.get('key1'); // print data
  {data: 'test'}

> ls.set('key2', [1, 2, 3]); // set another key
> ls.getAllKeys(); // get all keys
  ["key1", "key2"]
> ls.removeAll(); // remove all keys

API Documentation

Create an instance / reference before using.

var ls = new SecureLS();

Contructor accepts a configurable Object with all three keys being optional.

Config Keys default accepts
encodingType Base64 base64/aes/des/rabbit/rc4/''
isCompression true true/false
encryptionSecret PBKDF2 value String
encryptionNamespace null String

Note: encryptionSecret will only be used for the Encryption and Decryption of data with AES, DES, RC4, RABBIT, and the library will discard it if no encoding / Base64 encoding method is choosen.

encryptionNamespace is used to make multiple instances with different encryptionSecret and/or different encryptionSecret possible.

var ls1 = new SecureLS({encodingType: 'des', encryptionSecret: 'my-secret-key-1'});
var ls2 = new SecureLS({encodingType: 'aes', encryptionSecret: 'my-secret-key-2'});

Examples:

  • No config or empty Object i.e. Default Base64 Encoding and Data compression
var ls = new SecureLS();
// or
var ls = new SecureLS({});
  • No encoding No data compression i.e. Normal way of storing data
var ls = new SecureLS({encodingType: '', isCompression: false});
  • Base64 encoding but no data compression
var ls = new SecureLS({isCompression: false});
  • AES encryption and data compression
var ls = new SecureLS({encodingType: 'aes'});
  • RC4 encryption and no data compression
var ls = new SecureLS({encodingType: 'rc4', isCompression: false});
  • RABBIT encryption, no data compression and custom encryptionSecret
var ls = new SecureLS({encodingType: 'rc4', isCompression: false, encryptionSecret: 's3cr3tPa$$w0rd@123'});

Methods

  • set

    Saves data in specifed key in localStorage. If the key is not provided, the library will warn. Following types of JavaScript objects are supported:

    • Array
    • ArrayBuffer
    • Blob
    • Float32Array
    • Float64Array
    • Int8Array
    • Int16Array
    • Int32Array
    • Number
    • Object
    • Uint8Array
    • Uint8ClampedArray
    • Uint16Array
    • Uint32Array
    • String
    Parameter Description
    key key to store data in
    data data to be stored
      ls.set('key-name', {test: 'secure-ls'})
    
  • get

    Gets data back from specified key from the localStorage library. If the key is not provided, the library will warn.

    Parameter Description
    key key in which data is stored
      ls.get('key-name')
    
  • remove

    Removes the value of a key from the localStorage. If the meta key, which stores the list of keys, is tried to be removed even if there are other keys which were created by secure-ls library, the library will warn for the action.

    Parameter Description
    key remove key in which data is stored
      ls.remove('key-name')
    
  • removeAll

    Removes all the keys that were created by the secure-ls library, even the meta key.

      ls.removeAll()
    
  • clear

    Removes all the keys ever created for that particular domain. Remember localStorage works differently for http and https protocol;

      ls.clear()
    
  • getAllKeys

    Gets the list of keys that were created using the secure-ls library. Helpful when data needs to be retrieved for all the keys or when keys name are not known(dynamically created keys).

    getAllKeys()

      ls.getAllKeys()
    

Screenshot

Scripts

  • npm run build - produces production version of the library under the dist folder
  • npm run dev - produces development version of the library and runs a watcher
  • npm run test - well ... it runs the tests :)

Contributing

  1. Fork the repo on GitHub.
  2. Clone the repo on machine.
  3. Execute npm install and npm run dev.
  4. Create a new branch <fix-typo> and do your work.
  5. Run npm run build to build dist files and npm run test to ensure all test cases are passing.
  6. Commit your changes to the branch.
  7. Submit a Pull request.

Development Stack

  • Webpack based src compilation & bundling and dist generation.
  • ES6 as a source of writing code.
  • Exports in a umd format so the library works everywhere.
  • ES6 test setup with Mocha and Chai.
  • Linting with ESLint.

Process

ES6 source files
       |
       |
    webpack
       |
       +--- babel, eslint
       |
  ready to use
     library
  in umd format

Credits

Many thanks to:

Copyright and license

The MIT license (MIT)

Copyright (c) 2015-2016 Varun Malhotra

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

secure-ls's People

Contributors

dependabot[bot] avatar hansanwok avatar konsultaner avatar luish avatar shukob avatar softvar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

secure-ls's Issues

Security issue

I think your design is flawed. You are not really providing any security without random values unique to each domain and user. Please refer to NIST SP 800-132 for more information.

Is it possible to set and decrypt with different LS instances (i.e. Cypress and FE Framework)

I assume each app instance has its own secureLS instance with its own salt, such that one SecureLS can't decrypt a token set by another SecureLS. I get that that is a big point of security, but my use case is logging in via an API call to the backend using LS to set the token into LS using Cypress for E2E testing. If Cypress runtime uses one secure-ls import and Vue uses another, is it even possible for these to talk, with the right configuration or is that an impossibility? We're getting a could not parse JSON error in Cypress's console from secure-ls.js:256 and that would make sense if this is not possible to decrypt

Error while using Secure-Ls in Angular strict mode

Hi,

I am using Secure-ls it was working nice when I was not using Angular in strict Mode but when I am using it in Angular strict mode then it is throwing exception.

Error: node_modules/secure-ls/dist/secure-ls.d.ts:4:9 - error TS2305: Module '"../../@types/crypto-js"' has no exported member 'CipherHelper'.

4 import {CipherHelper, Encoder} from 'crypto-js';
          ~~~~~~~~~~~~
node_modules/secure-ls/dist/secure-ls.d.ts:4:23 - error TS2305: Module '"../../@types/crypto-js"' has no exported member 'Encoder'.

4 import {CipherHelper, Encoder} from 'crypto-js';

image

@softvar Please provide solution for this

This is the repo here

Incompatible lz-string 1.5.0

At package.json there is

    "lz-string": "^1.4.4"

It will take version 1.5.0. Unfotnatelly this version is not compatible.

After all we have error:

Error: node_modules/secure-ls/dist/secure-ls.d.ts:24:24 - error TS2694: Namespace '".....node_modules/secure-ls/node_modules/lz-string/typings/lz-string"' has no exported member 'LZStringStatic'.

24     LZString: LZString.LZStringStatic;

If I force in my project "lz-string": "1.4.4" , version 1.5.0 will appear inside node_modules/secure-ls/node_modules.
There is no nice workaround with this, but only to delete this internal node_modules.

Please change dependencies to

    "lz-string": "1.4.4"

Could not Parse Json or t is null

Repo gives error could not parse json or t is null if the ls.get has a blank data and the further code do not run. i think repo tries to parse a blank data if ls.get data has null value then repo should not try to decrypt the data, this problem occurs only in Mozilla Firefox version 61, i have not tested in older versions

Also the library is not working in Internet Explorer and Microsoft Edge with the invalid argument error

I initialized the object SecureLs in head, i successfully stored the data in local storage with aes is encryption, i closed my browser and opened again and when i reached the page it says t is null, but i was surprised that this happens only in Mozilla Firefox (works fine in chrome and safari)

Has no default export

Hy, when i try to import in to my angular6 project:
import SecureLS from 'secure-ls'

but i receive this messages:

ERROR in node_modules/secure-ls/dist/secure-ls.d.ts(12,21): error TS1122: A tuple type element list cannot be empty.
src/app/pages/login/login.component.ts(16,8): error TS1192: Module
"node_modules/secure-ls/dist/secure-ls" has no default export.

Can anyone help me, with this?

Not able to fetch value from different origin

We are using this in salesforce lighting and classic. The only issue is, when we try to set a localstorage value from VisualForce page, it gets set in different origin, for eg; https://testdev--c.cs9.visual.force.com, but when we try to set it from lightning it gets set in https://testdev--lightning.force.com.

This is normal. but the strange thing is I am able to view the keys of "https://testdev--c.cs9.visual.force.com" origin while accessing ls.getAllKeys() from "https://testdev--lightning.force.com", but the values aren't available even if I use the same secret key.

How to encrypt sessionStorage using vuex-persistedstate?

  • vuex-persistedstate version: 4.0.0
  • node version: 14.17.0
  • npm (or yarn) version: 6.14.13
  • secure-ls version:1.2.6
  • vue version: 3.0.0
  • vuex version: 4.0.0

Relevant code or config

import { createStore, Store } from 'vuex';
import { State } from 'vue'
import user, { IUserInfoState } from './modules/user';
import global, { IGlobalState } from './modules/global';
import SecureLS from 'secure-ls'
import createPersistedState from 'vuex-persistedstate'

declare module '@vue/runtime-core' {
  interface State {
    user: IUserInfoState;
    global: IGlobalState;
  }
  interface ComponentCustomProperties {
    $store: Store<State>
  }
}

const ls = new SecureLS({ isCompression: false })
window.sessionStorage.getItem = (key) => ls.get(key) 
window.sessionStorage.setItem = (key, value) => ls.set(key, value)
window.sessionStorage.removeItem = (key) => ls.remove(key)

export default createStore<State>({
  modules: {
    user,
    global,
  },
  plugins: [
    createPersistedState({ storage: window.sessionStorage })
  ]
});

I want to encrypt the sessionStorage using secure-ls. But with the code above, the secure-ls only encrypted the localStorage. I already issued this problem in the repository of vue-persistedstate. But they said this is scure-ls's issue. Anyone knows why? Please do tell.

How secure is it really?

Heya, i'm sorry if this is a stupid question, i'm no security expert.
but if everything has to be two-way, then the secret has to be accessible for every attacker... right?
so is it really just obfuscating the data, or is there a real encryption at work here, which is hard (or virtually impossible?) to break?

would someone explain it to me?
thanks :)

Object doesn't save on mac

any javascript Object doesn't save on local storage on mac devices only, but other device working finely

Error: Malformed UTF-8 data

When trying to get a value from localStorage using the get() method, I receive an error stating

Error: Malformed UTF-8 data

This only happens when using non-Base64 encoding.

The stack trace shows:

Error: Malformed UTF-8 data
    at Object.stringify (secure-ls.js:1845)
    at init.toString (secure-ls.js:957)
    at SecureLS.get (secure-ls.js:248)

Error: Malformed UTF-8 data

Error: Malformed UTF-8 data
this error occurs in every 3 to 4 days
while after clearing the local Storage Data solve this error but user cannot do the same is there any alternative for this issue ?
or can you fix this bug ?

Can you release a new version with correct typings

declare namespace SecureLS{
interface Base64 {
_keyStr: string;
encode(e: string);
decode(e: string);
}
}

is in the latest published version on npm.

Typescript complains with:

ERROR in ./node_modules/secure-ls/dist/secure-ls.d.ts
39:9 'decode', which lacks return-type annotation, implicitly has an 'any' return type.
37 | _keyStr: string;
38 | encode(e: string);

39 | decode(e: string);
| ^
40 | }
41 | }

Non compatible anymore with Vuex (Vue.js State Store)

'use strict';
// https://github.com/championswimmer/vuex-persist#readme
import createPersistedState from 'vuex-persistedstate';

import SecureLS from 'secure-ls';

const encryptedLocalStorage = new SecureLS(
    {
        encodingType: 'aes',
        encryptionSecret: 'D#xsQ6>P(_)Wrw;A',
        isCompression: false,
    },
);

const plugins = [
    createPersistedState({
                             storage: {
                                 getItem:    key => encryptedLocalStorage.get(key),
                                 setItem:    (key, value) => encryptedLocalStorage.set(key, value),
                                 removeItem: key => encryptedLocalStorage.remove(key),
                             },
                         }),
];

export default plugins;

import plugins                from './plugin/plugins';
import Vuex, {ModuleTree}     from 'vuex';
import Vue                    from 'vue';

Vue.use(Vuex);
const store = new Vuex.Store(
    {
        strict: 'production' !== process.env.NODE_ENV,
        devtools:  'production' !== process.env.NODE_ENV,
        modules,
        plugins,
    },
);
export default store;

Impossible to clear, update cached, encoded values. They are always old, outdated which cause a lot of issues, like expired token and its impossible to replace it.
Possibly related to
https://github.com/championswimmer/vuex-persist#readme
and
removeItem: key => encryptedLocalStorage.remove(key),

 "secure-ls": "^1.2.6",
    "source-map-loader": "^0.2.4",
    "standard": "^14.3.1",
    "uglifyjs-webpack-plugin": "^2.1.3",
    "url-loader": "^4.1.1",
    "vue": "^2.6.11",
    "vue-class-component": "^7.2.3",
    "vue-property-decorator": "^9.1.2",
    "vue-resource": "^1.2.1",
    "vue-router": "^3.0.1",
    "vue-router-multiguard": "^1.0.3",
    "vue-style-loader": "^4.1.0",
    "vue-template-loader": "^1.1.0",
    "vuex": "^3.0.1",
    "vuex-class": "^0.3.2",
    "vuex-persistedstate": "^4.0.0-beta.3",
    "vuex-router-sync": "^5.0.0"

Using Secure-LS

I'm using secure ls for a single page app.
When my web page loads I need a way to detect if there is an existing instance of secure-ls.
If I invoke lib = new SecureLS() each time I reload the page the current instance is overwritten and all data
from the previous session is lost.

I use onload() callback to initalize secureLS. Is there a way around this issue?

Allow us to have own meta key

Not highest priority, but it would be nice if we could choose our own _secure_ls_metadata to cover up bit more.

encryptionNamespace just add another string to "_secure_ls_metadata"

Not working with Microsoft Edge

While encrypting the local storage using secure-ls, its running fine in Chrome, Firefox but the entire app is not showing when running with Edge.

secure-ls ( v.^1.2.6") can't find variable localStorage

I am trying to use secure-ls to encrypt local data of my Parse Server Application in a react-native project.
when typing the following two lines, I get the error "secure-ls can't find variable localStorage":

import SecureLS from 'secure-ls';
const ls = new SecureLS({ isCompression: false });

Could you tell me how to fix this error?

SecureLS and Microsoft Edge Local Storage

There is a problem with Microsoft Edge Local Storage and SecureLS. The problem is as explained here .

I managed to make it work on Edge by settings the compression off like this:
new SecureLS({ encodingType: 'aes', isCompression: false, encryptionSecret: '60f697d5-9aa9-4af3-a3e8-c1d4952fc7c2' });

But still there are problems as _secure_ls_metadata is not set.

Add support for custom storage type

Adding support for a different storage type like sessionStorage or a custom solution might be useful. I made and tested the changes in a fork, PR coming soon.

.clear() erase all namespaces

Hi, I don't know if this is intentional.

When using multiple nameSpaces then using clear(), all localStorage get deleted.

[FEATURE] Comply with Storage API for drop-in replacement of a unencrypted localStorage

  • Actual behavior:
    If a user wants to switch from a unencrypted localStorage to secure-ls, he/she has to rewrite most of the current storage method calls as secure-ls uses different APIs (e.g. get(key) instead of getItem(key) and so on )

-Desired behavior
In order to simplify secure-ls adoption in place of a unencrypted storage, if it could comply the Storage API https://developer.mozilla.org/en-US/docs/Web/API/Storage this could make a developer life much easier, and allow better third party integration.

This would require implementing the five Storage interface methods:
Storage.key()
Storage.getItem()
Storage.setItem()
Storage.removeItem()
Storage.clear()

or just remap current method names

Firefox issue - TypeError: e is null

Hi,

Firefox 54.0 (64-bit) osX is returning this error: TypeError: e is null...

// },
/
9 /
/
/
.
.
.
e = e.replace(/[^A-Za-z0-9\+\/\=]/g, '');

Line 1900

Firefox

It look like firefox can't process the secure ls. On shutdow browser and relaod the store wont react. I have to remove de storage before it wil load again.

In Chrome everything works fine

@types/crypto-js"' has no exported member 'CipherHelper' & 'Encoder'

Hello,

I trying to build my project with quasar (vuejs) but i got those errors :

ERROR in .../node_modules/secure-ls/dist/secure-ls.d.ts(4,9): TS2305: Module '"../../@types/crypto-js"' has no exported member 'CipherHelper'.

ERROR in /home/jer/leihia/leihia-vuejs/node_modules/secure-ls/dist/secure-ls.d.ts(4,23): TS2305: Module '"../../@types/crypto-js"' has no exported member 'Encoder'

I got that in my index.ts (store) :

var ls = new SecureLS({});

so I changed to this:

import * as SecureLS from 'secure-ls'
var ls = new SecureLS({});

But stil got original error messages + another one :
TS2351: This expression is not constructable. Type 'typeof SecureLS' has no construct signatures.

Tried with last version even 1.2.5.

I would love any help cause your solution is perfect for my project.
Thanks!

how to delete key

how to remove data when encryptionSecret change rather then throw off error
I do test with default setting then later change the encryptionSecret unable to access my app till I clear all the stored data

Empty password is revealing everything

I used the demo here: and set up some data in the SecureLS with a password, and encryption system is AES.

Then in the browser console of same page I deliberately created another instance of SecureLS but this time with empty password

var ls = new SecureLS({encodingType: 'aes', isCompression: true, encryptionSecret: ""});
then i wrote console.log(ls)

It revealed everything. How come? Maybe I have misunderstood something?

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.