How to Encrypt and Decrypt in Angular 6

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

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.


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.


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