How To sent json data into query string in encrypt in c# and decrypt form and get back in normal json format in angular(from c# mvc webapi to angular & angular to c# mvc webapi )

 How To sent json data into query string in encripted form and get back in normal json format in angular(from c# mvc webapi to angular & angular to c# mvc webapi) 

As per topic we are explain how to encrypt data from c# asp.nt mvc webapi to angular 6/7/8/9 front end side decrypt , in this blog we explain that how we can either encrypt from c# and decrypt from angular side and wise versa. and also used atob and btoa mechenism from c# and convert wise versa from angular side. 

Asp.net:

using Newtonsoft.Json;
using System;
using System.IO;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Web.Http;
namespace EncriptionDecription.Controllers
{
    [RoutePrefix("api/encript")]
    public class encriptController : ApiController
    {
        // GET: encript
        [Route("GetEncripiton")]
        public IHttpActionResult GetEncripiton(string data)
        {
            return base.ResponseMessage(new HttpResponseMessage()
            {
Content = new StringContent(EncodeTo64(EncryptStringAES(data)), Encoding.UTF8,"text/html")               
            });
           
        }

        [Route("GetDecripiton")]
        public IHttpActionResult GetDecripiton(string data)
        {
            return base.ResponseMessage(new HttpResponseMessage(){
                Content = new StringContent( DecryptStringAES(data), Encoding.UTF8, "text/html" )
            });
        }

        public static string DecryptStringAES(string cipherText)
        {
            var keybytes = Encoding.UTF8.GetBytes("mysecretkey");
            var iv = Encoding.UTF8.GetBytes("mysecretkey");
           // var encrypted = Convert.FromBase64String(cipherText);           
            byte[] encrypted = Convert.FromBase64String(DecodeFrom64(cipherText.Replace(' ', '+')));
           // byte[] encrypted = Encoding.ASCII.GetBytes(cipherText);
            var decriptedFromJavascript = DecryptStringFromBytes(encrypted, keybytes, iv);
            return JsonConvert.SerializeObject(decriptedFromJavascript);
            //return string.Format(decriptedFromJavascript);
        }
        private static string DecryptStringFromBytes(byte[] cipherText, byte[] key, byte[] iv)
        {
            // Check arguments.  
            if (cipherText == null || cipherText.Length <= 0)
            {
                throw new ArgumentNullException("cipherText");
            }
            if (key == null || key.Length <= 0)
            {
                throw new ArgumentNullException("key");
            }
            if (iv == null || iv.Length <= 0)
            {
                throw new ArgumentNullException("key");
            }

            // Declare the string used to hold  
            // the decrypted text.  
            string plaintext = null;

            // Create an RijndaelManaged object  
            // with the specified key and IV.  
            using (var rijAlg = new RijndaelManaged())
            {
                //Settings  
                rijAlg.Mode = CipherMode.CBC;
                rijAlg.Padding = PaddingMode.PKCS7;
                rijAlg.FeedbackSize = 128;

                rijAlg.Key = key;
                rijAlg.IV = iv;

                // Create a decrytor to perform the stream transform.  
                var decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);

                try
                {
                    // Create the streams used for decryption.  
                    using (var msDecrypt = new MemoryStream(cipherText))
                    {
                        using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                        {

                            using (var srDecrypt = new StreamReader(csDecrypt))
                            {
                                // Read the decrypted bytes from the decrypting stream  
                                // and place them in a string.  
                                plaintext = srDecrypt.ReadToEnd();

                            }

                        }
                    }
                }
                catch
                {
                    plaintext = "keyError";
                }
            }

            return plaintext;
        }

        public static string EncryptStringAES(string plainText)
        {
            var keybytes = Encoding.UTF8.GetBytes("mysecretkey");
            var iv = Encoding.UTF8.GetBytes("mysecretkey");

            var encryoFromJavascript = EncryptStringToBytes(plainText, keybytes, iv);
            return Convert.ToBase64String(encryoFromJavascript);
        }


        private static byte[] EncryptStringToBytes(string plainText, byte[] key, byte[] iv)
        {
            // Check arguments.  
            if (plainText == null || plainText.Length <= 0)
            {
                throw new ArgumentNullException("plainText");
            }
            if (key == null || key.Length <= 0)
            {
                throw new ArgumentNullException("key");
            }
            if (iv == null || iv.Length <= 0)
            {
                throw new ArgumentNullException("key");
            }
            byte[] encrypted;
            // Create a RijndaelManaged object  
            // with the specified key and IV.  
            using (var rijAlg = new RijndaelManaged())
            {
                rijAlg.Mode = CipherMode.CBC;
                rijAlg.Padding = PaddingMode.PKCS7;
                rijAlg.FeedbackSize = 128;

                rijAlg.Key = key;
                rijAlg.IV = iv;

                // Create a decrytor to perform the stream transform.  
                var encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);

                // Create the streams used for encryption.  
                using (var msEncrypt = new MemoryStream())
                {
                    using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (var swEncrypt = new StreamWriter(csEncrypt))
                        {
                            //Write all data to the stream.  
                            swEncrypt.Write(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }
            // Return the encrypted bytes from the memory stream.  
            return encrypted;
        }


        static public string EncodeTo64(string toEncode)
        {
            byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
            string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
            return returnValue;
        }
        static public string DecodeFrom64(string encodedData)
        {
            byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);
            string returnValue = System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);
            return returnValue;
        }

    }
}

Angular:-

1).Encryption decryption service

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

@Injectable({
    providedIn: 'root'
})

export class EncrDecrService {
    saltKeys = 'mysecretkey';

    constructor() { }
   set(value) {
        const key = CryptoJS.enc.Utf8.parse(this.saltKeys);
        const iv = CryptoJS.enc.Utf8.parse(this.saltKeys);
        const encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(value.toString()), key,
            {
                keySize: 128 / 8,
                iv: iv,
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.Pkcs7
            });

        return encrypted.toString();
    }

    // The get method is use for decrypt the value.
    get(value) {
        const key = CryptoJS.enc.Utf8.parse(this.saltKeys);
        const iv = CryptoJS.enc.Utf8.parse(this.saltKeys);
        const decrypted = CryptoJS.AES.decrypt(value, key, {
            keySize: 128 / 8,
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        });
        return decrypted.toString(CryptoJS.enc.Utf8);
    }

}

mail-redirection component


import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { ApiService } from '../../services/api.service';
import { CommonService } from '../../services/common.service';
import { EncrDecrService } from '../../services/EncrDecrService';
import { LoggerService } from '../../services/log4ts/logger.service';
import { SpinnerService } from '../../services/spinner.service';
import { BrowserStorageService } from '../../utility/browser-storage.service';

@Component({
  selector: 'app-mail-redirection',
  templateUrl: './mail-redirection.component.html',
  styleUrls: ['./mail-redirection.component.scss']
})
export class MailRedirectionComponent implements OnInit {
  public module = '';
  public page = '';
  public userId = '';
  constructor(private router: Router, private route: ActivatedRoute, private browserStorageService: BrowserStorageService,
    private commonService: CommonService, private loggerService: LoggerService, private spinner: SpinnerService,
    private apiService: ApiService, private encService: EncrDecrService) {
    // this.route.paramMap.subscribe(params => {
    try {
      this.urlData = this.route.snapshot.queryParamMap.get('data');
      //first deco url data into birnary
      //then decoded binary url data into decription 
      //then convert back to json
      const data = JSON.parse(this.encService.get(atob(this.urlData)));
    } catch (error) {
      this.router.navigate(['dashboard/' + new Date().getTime()]);
      console.log(error);
    }
    // });
  }

  ngOnInit(): void {
    try {
      this.LoginuserId = this.browserStorageService.getLocalStorageItem('userId');
      if (this.userId && this.LoginuserId && this.userId.trim() === this.LoginuserId.trim()) {
        this.getViewTags();
      } else {
        this.router.navigate(['dashboard/' + new Date().getTime()]);
      }
    } catch (error) {
      this.router.navigate(['dashboard/' + new Date().getTime()]);
      console.log(error);
    }
  }


How To sent json data into query string in encripted form and get back in normal json format in angular

How To sent json data into query string in encripted form and get back in normal json format in angular


for encripted query string paramter json data i have follow steps 

1).first i have json data belongs to perticular page
like :-

    {
      module: 'tradefast',
      page: 'iot',
      userId: this.userId,
      TradeID: this.TradeID,
      CounterPartyID: this.CounterPartyID,
      Status: this.Status,
      contractFromEnumID: 'Online'
    }

2).convert json data into string data 

    var rowData = JSON.stringify({
      module: 'tradefast',
      page: 'iot',
      userId: this.userId,
      TradeID: this.TradeID,
      CounterPartyID: this.CounterPartyID,
      Status: this.Status,
      contractFromEnumID: 'Online'
       });

3).then Convert JSON string to Encripted data 
     const encriptedData =this.encService.setEnc(rowData);

4).Then Convert encripted data into "btoa" formated string
    const btoaData=btoa(encriptedData);

5).Append query string with url
    const url='http://localhost:4200/#/mail-page?data='+btoaData;

6).Now Add link with perticular mail or in webpage
    <a href=""+url+"">Click Here</a>

7).Now When press click here anchor or link to redirect link page and get data query string
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import * as CryptoJS from 'crypto-js';
import { EncrDecrService } from '../../services/EncrDecrService';

@Component({
  selector: 'app-mail-page',
  templateUrl: './mail-page.component.html',
  styleUrls: ['./mail-page.component.scss']
})

export class MailRedirectionComponent implements OnInit {
public urlData='';
 constructor(private routerRouterprivate routeActivatedRoute,
 private encServiceEncrDecrService) {
 this.urlData = this.route.snapshot.queryParamMap.get('data');
  const data = JSON.parse(this.encService.getDec(atob(this.urlData)));
//print json data
console.log(data);
}
}

this is the component where we can get querystring and convert back into a proper json data with secure way there are first we convert url data into "atob" and then convert from "atob" to encripted form and then encripted form to decript into a json string and then finaly json string parse and get proper json data
and 
the security algorith that you used is used



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

@Injectable({
    providedIn: 'root'
})

export class EncrDecrService {
    saltKeys = 'yoursaltKey';

    constructor() { }

    // The set method is use for encrypt the value.
    set(value) {
            return this.setEnc(value);
    }

    // The get method is use for decrypt the value.
    get(value) {       
            return this.getDec(value);        
    }

    setEnc(value) {
        const key = CryptoJS.enc.Utf8.parse(this.saltKeys);
        const iv = CryptoJS.enc.Utf8.parse(this.saltKeys);
        const encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(value.toString()), key,
            {
                keySize: 128 / 8,
                iv: iv,
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.Pkcs7
            });
        return encrypted.toString();
    }

    // The get method is use for decrypt the value.
    getDec(value) {
        const key = CryptoJS.enc.Utf8.parse(this.saltKeys);
        const iv = CryptoJS.enc.Utf8.parse(this.saltKeys);
        const decrypted = CryptoJS.AES.decrypt(valuekey, {
            keySize: 128 / 8,
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        });

        return decrypted.toString(CryptoJS.enc.Utf8);

    }


Featured Post

how to find duplicate item from array using multiple object keys in angular or javascript

 how to find duplicate item from array using multiple object keys There is a way to find based of multiple key find duplicate records in ang...

Popular Posts