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


No comments:

Post a Comment

Thank You For Your Great Contribution

Featured Post

How to sent authorized header attribute value using c# .net httpclient for third party api call of oauth 2.0

How to sent authorized header attribute value using C# .NET HTTP client for third party API call of OAuth 2.0 For call token From Authorized...

Popular Posts