Search code examples
typescriptencryptionangular8cryptojsnode-crypto

How to encrypt and decrypt json data in angular 8


Tried to encript and decrypt the json data using crypto-js. But not working. How to find the solution. If anyone know please help to find the solution.

Demo : https://stackblitz.com/edit/angular-ivy-nwhkgz?file=src%2Fapp%2Fapp.component.ts

storageData=
[

  {

  "customerInfo": { 
    "Micheal": 1,
    "Milson": 2 
  },

  "mycart": {
    "Ol1": 1,
    "Ol3": 1
  },


  "cartItemsList": [
    {
      "pid": "Ol1",
      "name": "Avacota",
      "qty": 1 
    },
    {
      "pid": "Ol3",
      "name": "Kaliflower",
      "qty": 1 
    }
  ],
  
  "cartTotal": 2

  }

  ];
 
ngOnInit(){

//Encrypt Info
this.encryptInfo = encodeURIComponent(CryptoJS.AES.encrypt(this.storageData, 'secret key 123').toString());

console.log("encryptInfo");
console.log(this.encryptInfo);


//Decrypt Info
var deData= CryptoJS.AES.decrypt(this.encryptInfo, 'secret key 123'); 
this.decryptedInfo = decodeURIComponent(deData.toString(CryptoJS.enc.Utf8));   

console.log("decryptedInfo");
console.log(this.decryptedInfo);

}

Solution

  • First of all: I do not recommend you do this yourself for production use without consulting someone well versed in cryptography and web security.

    There are two mistakes that prevent the crypto part from working:

    1. The data you tried to encrypt is not a string. You should serialize (stringify) it before encryption. I did it in the fixed example using JSON.stringify, and later parsed it using JSON.parse on lines 51 & 59
    2. You used encodeURIComponent after the encryption, so the decodeURIComponent had to be done before decryption. See ln 58

    Here is the fixed stackblitz: https://stackblitz.com/edit/angular-ivy-h6zlcv?devtoolsheight=33&file=src/app/app.component.ts