How to Encrypt and Decrypt in Angular 6

2020-02-28 06:18发布

问题:

Login Response

{ code: 200, id: 4, msg: "success", user: "Sourav" }

I have a issue like i want to store id and user in Local Storage as Encrypted format.How can i do it using Angular 6?

回答1:

In one our project, we have used 'crypto-js' library. http://github.com/brix/crypto-js

import * as CryptoJS from 'crypto-js';

encryptData(data) {

    try {
      return CryptoJS.AES.encrypt(JSON.stringify(data), this.encryptSecretKey).toString();
    } catch (e) {
      console.log(e);
    }
  }

  decryptData(data) {

    try {
      const bytes = CryptoJS.AES.decrypt(data, this.encryptSecretKey);
      if (bytes.toString()) {
        return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
      }
      return data;
    } catch (e) {
      console.log(e);
    }
  }


回答2:

Encrypting things on client side has no sense, since the key would be either stored in Javascript code or sent through network. In both cases it's impossible to obfuscate.



回答3:

Though it's not perfect, window.btoa() will provide basic base-64 encoding, to avoid everyone reading the user data. This could be your quickest solution. As encryption on the client side is not secured, because everything that comes to the browser can be seen by the end user (Your code or Ajax call, etc), even your encryption key.



回答4:

You can use crypto.js to encrypt data. See this if you don't know how to use it with Angular.

Next, you put the encrypted data into your local storage. See this tutorial.



回答5:

You can also use secure-ls. No need to maintain the decryption key at client side.

import * as SecureLS from 'secure-ls';
export class StorageService { 

  private _ls = new SecureLS({ encodingType: 'aes' });
  constructor() {
  }

  set(key: string, value: any, expired: number = 0) {
    this._ls.set(key, value);
  }

  remove(key: string) {
    this._ls.remove(key);
  }

  get(key: string) {
    return this._ls.get(key);
  }

  clear() {
    this._ls.removeAll();
  }
}