lpd
lpd

Reputation: 417

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?

Upvotes: 20

Views: 109035

Answers (6)

Guerric P
Guerric P

Reputation: 31815

The technical solution for encrypting things on client side is probably to use the native crypto object which allows to perform cryptographic operations in the browser.

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
  • ...

Upvotes: 11

NIKHIL RATHORE
NIKHIL RATHORE

Reputation: 31

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
  }

  

   
}`

Upvotes: 0

Nabeel Khan
Nabeel Khan

Reputation: 5

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

Upvotes: -5

Pramod KP
Pramod KP

Reputation: 188

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();
  }
}

Upvotes: 0

Amaresh C.
Amaresh C.

Reputation: 599

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.

Upvotes: 6

Suresh Kumar Ariya
Suresh Kumar Ariya

Reputation: 9764

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);
    }
  }

Upvotes: 33

Related Questions