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

    }


How to remove multiple item from FormArray

 How to remove multiple item from FormArray


Call Method at any component :-
this.removeItems(formArray, formcontrolCountryID, 2); 

Method Defination :-

removeItems(formArray, formcontrolCountryID, TypeID) {
    const items: any = formArray.value.filter(x => x.CountryID == formcontrolCountryID.value && x.TypeID == TypeID);
    if (items && items.length > 0) {
      formArray.controls.forEach((element, j) => {
        if (element.get('CountryID').value == formcontrolCountryID.value && element.get('TypeID').value == TypeID) {
          formArray.removeAt(j);
        }
      });
      this.removeItems(formArray, formcontrolCountryID, TypeID);
    }


  }


How to get Token of mvc in angular 6/ angular 9

 How to get Token of mvc in angular 6/ angular 9



For calling MVC Token we are divide process into three steps:-

Step1:-

getCSharpMVCToken(userData) {

    return new Promise((resolve, reject) => {

      const data = {

        'userName': this.loginForm.get('userName').value,

        'password': userData.uuid

      };

      this.authService.getCSharpMVCToken(data).then(tokenRes => {

        // this.userService.saveUserActivityLog(Constants.USER_ACTIVITIES.USER.NAME, Constants.NO_COMMENTS,

        //   Constants.USER_ACTIVITIES.OPERATIONS.LOGIN, Constants.NO_COMMENTS);

        return resolve(true);

      }).catch(err => {

        this.toggleSpinner(false);

        this.authService.logout();

        return reject(false);

      });

    });

  }

  

Step2:-

getCSharpMVCToken(data): Promise<any> {

        return new Promise((resolve, reject) => {

            if (this.alfAuthuthService.isEcmLoggedIn()) {

                this.apiService.getCSharpMVCToken(environment.CSharpMVCTokenApi, data).subscribe((res: any) => {

                    this.browserStorageService.setLocalStorageItem('CSharpMVCToken', res['access_token']);

                    return resolve(res);

                }, (err) => {

                    reject(err);

                });

            } else {

                reject(false);

            }


        });

           }

Step1:-

getCSharpMVCToken(URL, user: any) {

    const userData = 'username=' + user.userName + '&password=' + user.password + '&grant_type=password';

    const reqHeader = new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' });

    const response = this.http.post(URL, userData, { headers: reqHeader }).pipe(map((res => {

      return res;

    })), catchError((error: any) => {

      return this.httpErrorHandler.handleError('api-service', error, URL);

    }));


    return response;

  }



How to solved ngx-multiselect in angular cause long page scroll when we select item of it

How to solved ngx-multiselect in angular cause long page scroll when we select item of it



For solving this issue please put css on it


.dropdown-list{
    display:grid;
}

it just stop scroll of page

How to Create excel file and download it or convert into base64 string

How to Create excel file and download it or convert into base64 string

1).First Install Following packages from Node module
1).npm install exceljs
page Url:https://www.npmjs.com/package/exceljs
2).npm install file-saver --save
page Url:https://www.npmjs.com/package/file-saver
Code Writing:-


import * as Excel from 'exceljs/dist/exceljs';
import * as FileSaver from 'file-saver';
import { Injectable } from '@angular/core'; @Injectable({
providedIn: 'root', }) export class HeroService { constructor() { }
public generateExcel(paramData: any, _ReferenceNo, IsSend = false): any { return new Promise((resolve, reject) => { if (IsSend) { return this.workbook.xlsx.writeBuffer({ base64: true }).then((data) => { const itemdata = new Blob([data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }); const reader = new FileReader(); reader.readAsDataURL(itemdata); reader.onloadend = function () { return resolve(reader.result.toString().replace('data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,', '')); } }); } else { this.workbook.xlsx.writeBuffer().then((data) => { const blob = new Blob([data], { type: EXCEL_TYPE }); FileSaver.saveAs(blob, _ReferenceNo ? _ReferenceNo : 'temporary' + EXCEL_EXTENSION); return resolve(data); }); } }); }
}
Calling Method to component:- 


this.pdfService.generatePDF(this.trademodel, true, false).then(resp=>{
postJson.PdfString=resp;
});





How to Create pdf file and download it or convert into base64 string

 

How to Create pdf file and download it or convert into base64 string


1).First Install Following packages from Node module
1).npm install jspdf --save
page Url:https://www.npmjs.com/package/jspdf
2).npm install jspdf jspdf-autotable
page Url:https://www.npmjs.com/package/jspdf-autotable
Code Writing:-


import * as jspdf from 'jspdf'; import 'jspdf-autotable'; import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', }) export class HeroService { constructor() { } generateXml(data,UseType,IsGenerate){ const pdf= new jsPDF(); pdf.autoTable({ html: '#my-table' }) // Or use javascript directly: pdf.autoTable({ head: [['Name', 'Email', 'Country']], body: [ ['David', 'david@example.com', 'Sweden'], ['Castille', 'castille@example.com', 'Spain'], // ... ], }) if (IsGenerate) { pdf.save(data.ReferenceNo + '.pdf'); return ''; } else { return pdf.output('datauristring').replace('data:application/pdf;filename=generated.pdf;base64,', ''); } }

Now Need to Call Service in Your Component:-
 postJson.PdfString = this.pdfService.generatePDF(this.trademodel, true, false);

How to Create xml file and download it or convert into base64 string

 How to Create xml file and download it or convert into base64 string


1).First Install Following packages from Node module
1).npm install xml-writer
page Url:https://www.npmjs.com/package/xml-writer
2).npm install file-saver --save
page Url:https://www.npmjs.com/package/file-saver
Code Writing:-


import * as XMLWriter from 'xml-writer';
import * as FileSaver from 'file-saver';

import { Injectable } from '@angular/core'; @Injectable({
providedIn: 'root', }) export class HeroService { constructor() { }
generateXml(data,type,IsGenerate){

var XMLWriter = require('xml-writer');
xw = new XMLWriter;
xw.startElement('root').writeAttribute('foo', 'value')
.text('Some content');

if (IsGenerate) { const blob = new Blob([this.xw], { type: 'application/xml;charset=UTF-8' }); FileSaver.saveAs(blob, paramData.ReferenceNo + '.xml'); return ''; } else { return this.xw.output; }

}
}
Now Need to Call Service in Your Component:-
postJson.XMLString = btoa(this.dealFastXMLService.generateXml(this.trademodel, true, false));

Featured Post

How to remove all quick access file from computer in one time

 How to remove all quick access file from computer in one time  step1: first at all press "Window+R" then open a Run dialog box an...

Popular Posts