Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Encrypt and Decrypt in Angular 6

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?

like image 302
lpd Avatar asked Nov 26 '18 10:11

lpd


3 Answers

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);
    }
  }
like image 200
Suresh Kumar Ariya Avatar answered Sep 18 '22 21:09

Suresh Kumar Ariya


The technical solution for encrypting things on client side is probably to use some third party library. Quoting such libraries leads to opinionated answers and that's not very desirable here.

However, if the use case is to hide some backend data from the user (which seems to be the case when I read your question), it makes no sense to encrypt, since the key would be either stored in JavaScript code or sent through network. In both cases it's impossible to obfuscate.

Some examples of valid use cases for client-side encryption:

  • Allow the user to encrypt things with a key they own.
  • Use some public key to encrypt a message for a system that owns the corresponding private key
  • ...
like image 37
Guerric P Avatar answered Sep 18 '22 21:09

Guerric P


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.

like image 22
Amaresh C. Avatar answered Sep 17 '22 21:09

Amaresh C.