Data Encryption And Decryption In Angular 12

Hello friends, As we know, for better security purposes modern web development requires data encryption to encrypt sensitive user data. In this article, we will learn about data Encryption and Decryption in Angular 12 using Crypto js.

What is Encryption?

Encryption is the process of taking plain text and converting it into an unreadable format also known as Ciphertext. This helps protect the confidentiality of digital data either stored on computer systems or transmitted through a network like an internet.

What is Decryption?

Decryption is the process of taking Ciphertext and converting it into a readable format also known as Plaintext.

We use the same key to encrypt the data and with the same key, we can decrypt the data. This means a single key is required for data Encryption and Decryption.

Let us understand it with an example.

First, create a new project in Angular using this command.

ng EncryptionDecryptionApp

Open the AppModule.ts  and paste the following code into it.

import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Open the EncryptionServiceService.ts and paste the following code into it.

import { Injectable } from '@angular/core';
import * as CryptoJS from 'crypto-js';

@Injectable({
  providedIn: 'root'
})
export class EncryptionServiceService {

  key: string = "z!!!!!!!1sdfadsf56adf456asdfasdf";
  appProperties = {
    VALUES: {
      KEY: "MTIzNDU2Nzg5MEFCQ0RFRkdISUpLTE1O",
      IV: "MTIzNDU2Nzg="
    }
  }

  constructor() { }

  encryptionAES(encryptStr: any) {
    // Encrypt
    const ciphertext = CryptoJS.AES.encrypt(encryptStr, 'secret key 123');
    return ciphertext.toString();
  }

  decryptionAES(decryptStr: any) {
    // Decrypt
    const bytes = CryptoJS.AES.decrypt(decryptStr, 'secret key 123');
    const plaintext = bytes.toString(CryptoJS.enc.Utf8);
    return plaintext;
  }
}

Open the AppComponent.ts and paste the following code into it.

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { EncryptionServiceService } from './encryption-service.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  encryptpassword: string | any;
  decryptpassword: string | any;
  encryptForm = new FormGroup({
    encryptStr: new FormControl(),
    decryptStr: new FormControl()
  });

  decryptForm = new FormGroup({
    decryptStr: new FormControl()
  });

  constructor(private encrypt: EncryptionServiceService) { }

  ngOnInit() {
  }

  encryptData() {
    this.encryptpassword = this.encrypt.encryptionAES(this.encryptForm.value.encryptStr);
  }
  decryptData() {
    this.decryptpassword = this.encrypt.decryptionAES(this.encryptpassword);
  }
}

Open the app.component.html and paste the following code into it.

<div class="container">
    <div class="row">
        <div class="col-10">
            <div class="jumbotron">
                <h2>Data Encryption And Decryption In Angular 12</h2>
                <form name="encryptForm" [formGroup]="encryptForm" (ngSubmit)="encryptData()">
                    <div class="form-group">
                        <label for="text">Plain text</label>
                        <input type="text" class="form-control" formControlName="encryptStr" />
                    </div>
                    <div class="form-group">
                        <button class="btn btn-primary">Encrypt</button>
                    </div>
                    <label>Output: {{encryptpassword}}</label>
                </form>
                <hr>
                <form name="decryptForm" [formGroup]="decryptForm" (ngSubmit)="decryptData()">
                    <div class="form-group">
                        <label for="text">Encrypted text</label>
                        <input type="text" class="form-control" formControlName="decryptStr"
                            value="{{encryptpassword}}" />
                    </div>
                    <div class="form-group">                                            
                        <button class="btn btn-primary">Decrypt</button>
                    </div>
                    <label>Output: {{decryptpassword}}</label>
                </form>
            </div>
        </div>
    </div>
</div>

Now add this CDN to your main index.html

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
   integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

Output

Conclusion

In this article, we have learned about data Encryption and Decryption in Angular 12 using Crypto js. You can download the code from my Github repository.

Also check, Generate Base64 String And Display Image In Angular 12

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories