1

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

}

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Nice. How to make this work replacing a function that returns Observable<any> i.e. consume a API service a rest call that returns encrypted string data, which needs to be decrypted on angular function i.e. http get/post<> and populated in a table etc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.