19

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?

Guerric P
  • 30,447
  • 6
  • 48
  • 86
lpd
  • 407
  • 3
  • 7
  • 19
  • use `npm install crypto-js` library – Sanoj_V Nov 26 '18 at 10:17
  • You can use [crypto.js](https://www.npmjs.com/package/crypto-js) to encrypt data. See [this](https://stackoverflow.com/questions/45068925/how-to-use-cryptojs-with-angular-4) if you don't know how to use it with Angular. Next, you put the encrypted data into your local storage. See this [tutorial](https://alligator.io/js/introduction-localstorage-sessionstorage/). – holydragon Nov 26 '18 at 10:18

6 Answers6

32

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);
    }
  }
Suresh Kumar Ariya
  • 9,516
  • 1
  • 18
  • 27
  • 5
    How should `this.encryptSecretKey` be kept? – Kumar Sidharth Aug 07 '19 at 09:52
  • 1
    @KumarSidharth - You will need some sort of authentication system provided via a back-end. On login, provide the encryption key with the user info within the same request. – Cody Tolene Aug 27 '19 at 15:48
  • @CodyTolene The key is a static string. So what is the point of getting it from the server? We can use one key from the code itself. – Abhi Mar 08 '21 at 11:17
11

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
  • ...
Guerric P
  • 30,447
  • 6
  • 48
  • 86
7

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.

Amaresh C.
  • 579
  • 5
  • 17
  • we are passing http response as encrypted as storing key to decrpt in our javascript code (env file in angular ) is it secure? – Mohammed Jul 04 '22 at 05:53
0

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();
  }
}
Pramod KP
  • 188
  • 2
  • 8
0

This is how I did encryption/decryption in Angular:

//profile-detail.component.ts

var userIdVal = this._AESEncryptDecryptService.get(this.Auth[0].UserID);
    this._AESEncryptDecryptService.encryptData(this.eCode);
    var UserIdEncrpt = this._AESEncryptDecryptService.encryptData(userIdVal);

//EncryptDecryptService.service.ts

export class AESEncryptDecryptServiceService {
  secretKey = 'YourSecretKeyForEncryption&Descryption'
  constructor() { }

  // QA/UAT secret key
  encryptSecretKey = 'mySecretKeyHere'
  tokenFromUI: string = '123456$#@$^@1ERF'
  // Prod secret key
  // encryptSecretKey = 'b14ca3428a4e1840bbce2ea2315a1814'
  // tokenFromUI: string = '7891@$#@$^@1@ERF'

  // 7891@230456$#@$^@1257@ERF

  //adding secret key

  //Data Encryption Function
  encryptData(msg) {

    var keySize = 256
    var salt = crypto.lib.WordArray.random(16)
    var key = crypto.PBKDF2(this.encryptSecretKey, salt, {
      keySize: keySize / 32,
      iterations: 100,
    })

    var iv = crypto.lib.WordArray.random(128 / 8)

    var encrypted = crypto.AES.encrypt(msg, key, {
      iv: iv,
      padding: crypto.pad.Pkcs7,
      mode: crypto.mode.CBC,
    })

    var result = crypto.enc.Base64.stringify(
      salt.concat(iv).concat(encrypted.ciphertext)
    )
    return result
  }

  decryptData(txt) {
    var key = crypto.enc.Base64.parse(this.encryptSecretKey)
    var iv = crypto.lib.WordArray.create([0x00, 0x00, 0x00, 0x00])
    var decrypted = crypto.AES.decrypt(txt, key, { iv: iv })
    return decrypted.toString(crypto.enc.Utf8)
  }

  // ========================================================

  encrypted: any = ''
  decrypted: string

  set(value) {
    var key = crypto.enc.Utf8.parse(this.tokenFromUI)
    var iv = crypto.enc.Utf8.parse(this.tokenFromUI)
    var encrypted = crypto.AES.encrypt(
      crypto.enc.Utf8.parse(value.toString()),
      key,
      {
        keySize: 128 / 8,
        iv: iv,
        mode: crypto.mode.CBC,
        padding: crypto.pad.Pkcs7,
      }
    )

    return encrypted.toString()
  }

  //The get method is use for decrypt the value.
  get(value) {
    var key = crypto.enc.Utf8.parse(this.tokenFromUI)
    var iv = crypto.enc.Utf8.parse(this.tokenFromUI)
    var decrypted = crypto.AES.decrypt(value, key, {
      keySize: 128 / 8,
      iv: iv,
      mode: crypto.mode.CBC,
      padding: crypto.pad.Pkcs7,
    })

    return decrypted.toString(crypto.enc.Utf8)
  }

  decryptUsingAES256(value) {
    let _key = crypto.enc.Utf8.parse(this.tokenFromUI)
    let _iv = crypto.enc.Utf8.parse(this.tokenFromUI)

    var decrpted = crypto.AES.decrypt(value, _key, {
      keySize: 128 / 8,
      iv: _iv,
      mode: crypto.mode.CBC,
      padding: crypto.pad.Pkcs7,
    }).toString(crypto.enc.Utf8)

    return decrpted
  }

  

   
}`
-1

Simply use the built-in function as follows:

const encodedData = btoa('Hello, world'); // encode a string        
localStorage.setItem("token", encodedData );

let accessToken = localStorage.getItem("token");
const decodedData = atob(accessToken ); // decode the string
codesnerd
  • 767
  • 2
  • 8
  • 23
Nabeel Khan
  • 13
  • 1
  • 8