Angular 10 Session Cookies and Data Encryption and Decryption Easiest Way
What is Cookie ??
Cookies are small packages of information that are typically stored by your browser and websites tend to use cookies for multiple things. Cookies persist across multiple requests and browser sessions, you should set them to store the data and they can be a great method for authentication in some web apps.
Do Cookies have limitations?
Yes, they do! typically we can only store no more than 20 cookies per web server and no more than 4KB of information in each cookie and they can last indefinitely you should choose to specify the max-age attribute.
What we are going to do Today?
We will set up cookies first while storing the data. we will apply AES Encryption using CryptoJS and store it in session cookies and while retrieving the data we will decrypt it into human-readable format. So are you excited!!
Setting Up Your Environment 😎
In order to play about with cookies in Angular 10 we’ll have to install the npm i ngx-cookie-service
library by typing the following within our project:
create your project ng new Session-Cookies and select routing and styles sheet of your choice after everything is done.
Implementation
Just follow these simple steps
npm i ngx-cookie-service
Add the cookie service to your app.module.ts
as a provider
Then, import and inject it into a constructor,
Set up Environment for Encryption and Decryption
npm i crypto-js
follow this code
app.component.html
Encryption:
varName = CryptoJS.AES.encrypt(msg, password).toString(); this.cookie.set( ‘key’, ‘Value to Store’);
Decryption:
this.conversionOutput = CryptoJS.AES.decrypt(msg, password).toString(CryptoJS.enc.Utf8);
this.textToConvert = this.cookie.get(‘key’);
app.component.ts
UI :
Just follow each and every step carefully. you don't need to learn these concepts again, I made this as simple as possible. if you liked this article just press that clap so that I can post more easy and useful content in the future.