Encrypting the client side local storage data usin

2019-02-07 08:53发布

问题:

I have a client side data storing in the localStorage. For security reasons i want to encrypt the data. Is there any way to encrypt/decrypt the client data(not server data) using Angularjs?

$scope.accountObj = {
        isErrorMsg:false,
        isReadonly:false,
        createAccountErr:false        
    }; 

回答1:

You could use cryptojs library for encrypting/decrypting your data. First you should generate some key to use in encryption process:

 var secretKey = 'your-secret-key';

Then you need method to store and claim data:

store : function (key, value) {
    var encryptedData = CryptoJS.AES.encrypt(angular.toJson(value), secretKey).toString();
    window.localStorage.setItem(key, encryptedData);
},

get : function (key) {
    var encryptedData = window.localStorage.getItem(key);

    if (!_.isNull(encryptedData))
        return angular.fromJson(CryptoJS.AES.decrypt(encryptedValue, secretKey).toString(CryptoJS.enc.Utf8));

    return null;
}

The only problem here is that secret key is stored on the client side and it's kind of breaking logics of such encryptions.



回答2:

These are probably the best out of the box solutions available for cryptography in Javascript until now.

https://www.w3.org/TR/WebCryptoAPI/ https://crypto.stanford.edu/sjcl/

However, you will probably wanna avoid cryptography on the browser if "security" is a concern and seeing as you don't trust the client machine with your localStorage.