Thursday, December 4, 2025

RSA Encryption and Decryption using Private and Public Key, client and server side

RSA Encryption and Decryption using Private and Public Key, client and server side

Here i used two approach 

1. Server Side Encryption (using Public Key) and Server Side Decryption (using Private Key)


using System;
using System.Security.Cryptography;
using System.Text;

public partial class RSA_RSAEncDec : System.Web.UI.Page
{
    string publicKey = "";
    string privateKey = "";


    /*
     * Very Use full Site to develop this functionality
    //https://raskeyconverter.azurewebsites.net/XmlToPem?handler=ConvertPEM
    // For Encryption we user Private key PEM like below sample public key format i.e.  
    -----BEGIN PUBLIC KEY-----
    MIIBIjANBgkqhki....
-----END PUBLIC KEY-----

    For Decryption we required XMl file hence generate using the PEM and result like this..
    xpuS70fWBZv.....AQAB

+m+08g5NTiFXrh5f0...

ywUa2jNho8BFlQobo.....59OegfABWdD9tH4Dn7....B1t1AKlSBYQnQ....v4iZ7IpuX4yc....YC5TWCHX2duUR0a.....
*/ protected void Page_Load(object sender, EventArgs e) { string PreFix = @"C:\Users\murdhusi\Downloads\Biometric (2)\Biometric\Murli\"; publicKey = System.IO.File.ReadAllText(PreFix + @"RSApublicKeyM.txt"); privateKey = System.IO.File.ReadAllText(PreFix + @"RSAprivateKeyM.txt"); } protected void btnEncrypt_Click(object sender, EventArgs e) { txtencrypt.Text = GenerateKeyAndEncrypt(); } protected void btnDecrypt_Click(object sender, EventArgs e) { txtdecrypt.Text = GetKeyandDecrypt(Convert.FromBase64String(txtencrypt.Text)); } #region For Encryption private string GenerateKeyAndEncrypt() { // Generate RSA key pair using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { // Convert the data to bytes string data = txtplain.Text;// "Hello, RSA! MURLi"; //lblMessage.Text += ("
Orignal data: " + data); byte[] dataBytes = Encoding.UTF8.GetBytes(data); // Encrypt the data using the public key byte[] encryptedData = EncryptData(dataBytes, publicKey); string encData = Convert.ToBase64String(encryptedData); // Store or transmit the encrypted data //lblMessage.Text += ("
Encrypted data: " + encData); return encData; } } static byte[] EncryptData(byte[] dataBytes, string publicKey) { //if (true) { using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { // Import the recipient's public key rsa.FromXmlString(publicKey); // Encrypt the data using the public key byte[] encryptedData = rsa.Encrypt(dataBytes, true); return encryptedData; } } } #endregion #region For Decryption private string GetKeyandDecrypt(byte[] encData) { string originalData = ""; string privateKeyXml = ""; // Retrieve the encrypted data byte[] encryptedData = null; // Get the encrypted data privateKeyXml = privateKey; encryptedData = encData; // Create an instance of RSACryptoServiceProvider using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { // Import the private key rsa.FromXmlString(privateKeyXml); // Decrypt the data using the private key byte[] decryptedData = rsa.Decrypt(encryptedData, true); // Convert the decrypted data back to its original form originalData = Encoding.UTF8.GetString(decryptedData); // Display the decrypted data //lblMessage.Text += ("
Decrypted data: " + originalData); } return originalData; } #endregion }

2. Client Side Encryption (using Public Key) and Server Side Decryption (using Private Key)

<script src="https://cdn.jsdelivr.net/npm/jsencrypt@latest/bin/jsencrypt.min.js"></script>

    <script src="js/jsencrypt.min.js"></script>


<!--Your custom script that uses JSEncrypt-->

<script type="text/javascript">

    // Define the encryption function with a single parameter (the data to be encrypted).

    function encrypt(data) {

        //debugger;

        var encrypt = new JSEncrypt(); // Create a new instance of the JSEncrypt library.


        public_key = `-----BEGIN PUBLIC KEY-----

MIIBIjANBgkqhkiG9w.....

-----END PUBLIC KEY-----`;

        

        encrypt.setPublicKey(public_key); // Set the public key for the encryption library.

        var encrypted = encrypt.encrypt(data); // Use the encrypt method of the library to encrypt the data.


        //console.log("encrypted Text: ", encrypted);

        return encrypted; // Return the encrypted data.

    }


let encData = encrypt("Text for encryption");

</script>


Download Sample Code from here 

Friday, October 31, 2025

Prototype Pollution Fixes


Follow below step to fix the prototype pollution fix. To Fix this issue include below shared JS file next to jQuery Library.

Prototype Pollution Fix

FYI Below image

Tuesday, July 22, 2025

Some Git Command

git init

git clone https://murlidIndigo@bitbucket.org/indigoconsultingpublicis/hdfc_dcemi_file_extract_order_service.git

git status

git add .         [Add all files]

git commit -m "Commit Message"  [For Commit the files]

git push  [Push changes on repository]

git switch UAT [Change branch]

git fetch [Get Files from Repository of all branches]

git rm -r --cached [Remove caching]

Thursday, April 10, 2025

Read XMl File data With namespace and without namespace

 

Suppose xml files is avaialble like this with namespace

<?xml version="1.0" encoding="UTF-8"?> <Document xmlns="http://abcd.org/onmags/schema"> <AuthReq> <MyData> Hi How are you </MyData> </AuthReq> </Document>

.Net Sample Code looks like this

#region With Namespace XmlDocument doc = new XmlDocument(); doc.Load(Server.MapPath("/Sample/request.xml")); var nms = new XmlNamespaceManager(doc.NameTable); nms.AddNamespace("nm", "http://abcd.org/onmags/schema"); XmlNode node = doc.DocumentElement.SelectSingleNode("/nm:Document/nm:AuthReq", nms); //XmlNode node = doc.DocumentElement.SelectSingleNode("/Document/AuthReq"); string request = node.InnerText.ToString(); #endregion =================================================================

Suppose xml files is avaialble like this without namespace

<?xml version="1.0" encoding="UTF-8"?> <Document> <AuthReq> <MyData> Hi How are you </MyData> </AuthReq> </Document>

.Net Sample Code looks like this

#region With Namespace XmlDocument doc = new XmlDocument(); doc.Load(Server.MapPath("/Sample/request.xml")); XmlNode node = doc.DocumentElement.SelectSingleNode("/Document/AuthReq"); string request = node.InnerText.ToString(); #endregion

Monday, March 3, 2025

Get Validation Error Message, Page.Isvaild False Section

if you wanted to know the route cause of error message then we can write below code in aso.net 

 foreach (BaseValidator validator in Page.Validators)

            {

                if (validator.Enabled && !validator.IsValid)

                {

                    // Put a breakpoint here

                    string clientID = validator.ClientID;

                    string aa = validator.ErrorMessage;

                }

            }

Monday, February 24, 2025

Session Kill on Page Refresh OR On Page/Browser refresh session kill in asp.net with c#

Create a Global Variable

bool IsPageRefresh = false;

Write Below Code on Page Load

  #region To Maintain Refresh event
  //Section of code checks if the page postback is due to genuine submit by user 
  //or by pressing "refresh" or F5
  if (!IsPostBack)
  {
       //Session.Abandon(); Session.Clear();
       ViewState["ViewStateId"] = System.Guid.NewGuid().ToString();
       Session["SessionId"] = ViewState["ViewStateId"].ToString();
  }
  else
  {
      if (ViewState["ViewStateId"] != null && Session["SessionId"] != null)
        {
          if (ViewState["ViewStateId"].ToString() != Session["SessionId"].ToString())
            {
               IsPageRefresh = true;
            }
        }

        Session["SessionId"] = System.Guid.NewGuid().ToString();
        ViewState["ViewStateId"] = Session["SessionId"].ToString();
    } 
    #endregion 

Check Global variable where you made the condition like on events

    #region To Maintain Refresh event
     if (IsPageRefresh)
        {
          Session.Abandon(); Session.Clear();
        }
    #endregion

    if (Session["MyFlag"] == null) Response.Redirect("invalid.aspx?msg=Session expired. ", true);

Friday, December 13, 2024

SecurityProtocol Setting in .Net, SSL/TLS Error Fixes

 #region SecurityProtocol Setting

                try

                { //try TLS 1.3

                    ServicePointManager.SecurityProtocol = (SecurityProtocolType)12288

                                                         | (SecurityProtocolType)3072

                                                         | (SecurityProtocolType)768

                                                         | SecurityProtocolType.Tls;

                }

                catch (NotSupportedException)

                {

                    try

                    { //try TLS 1.2

                        ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072

                                                             | (SecurityProtocolType)768

                                                             | SecurityProtocolType.Tls;

                    }

                    catch (NotSupportedException)

                    {

                        try

                        { //try TLS 1.1

                            ServicePointManager.SecurityProtocol = (SecurityProtocolType)768

                                                                 | SecurityProtocolType.Tls;

                        }

                        catch (NotSupportedException)

                        { //TLS 1.0

                            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

                        }

                    }

                }

                #endregion

Saturday, September 14, 2024

Received an invalid column length from the bcp client for colid Error while Bulk Upload in aspx c#

 I have created sample code to know the route cause of this issue.

So we can write code like this.

Sample code:-

#region bulkCopy

if (MyConnection.State == ConnectionState.Closed) MyConnection.Open();

DataTable dataTableName = GetDataTabletFromCSVFile(filenamestr1);

using (SqlBulkCopy bulkCopy = new SqlBulkCopy(MyConnection))

{

bulkCopy.DestinationTableName = "Destination_TBL_My_Name_Temp";

try

{

bulkCopy.WriteToServer(dataTableName);

}

catch (Exception ex)

{

WriteErrorLog_Debug("My_FileExtractService " + ex.Message.ToString() + " " + ex.StackTrace.ToString() + " / " + RefNo, "testTimer_Elapsed1");


string message = "";

if (ex.Message.Contains("Received an invalid column length from the bcp client for colid"))

{

string pattern = @"\d+";

Match match = Regex.Match(ex.Message.ToString(), pattern);

var index = Convert.ToInt32(match.Value) - 1;


FieldInfo fi = typeof(SqlBulkCopy).GetField("_sortedColumnMappings", BindingFlags.NonPublic | BindingFlags.Instance);

var sortedColumns = fi.GetValue(bulkCopy);

var items = (Object[])sortedColumns.GetType().GetField("_items", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(sortedColumns);


FieldInfo itemdata = items[index].GetType().GetField("_metadata", BindingFlags.NonPublic | BindingFlags.Instance);

var metadata = itemdata.GetValue(items[index]);

var column = metadata.GetType().GetField("column", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).GetValue(metadata);

var length = metadata.GetType().GetField("length", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).GetValue(metadata);

message = (String.Format("Column: {0} contains data with a length greater than: {1}", column, length));

}

string aa =  message;


WriteErrorLog_Debug("My_FileExtractService Detailed Exception " + message.ToString() + " " + ex.StackTrace.ToString() + " / " + RefNo, "testTimer_Elapsed1");

}

}

#endregion

Wednesday, January 17, 2024

Get Web Request Error 500,400 Exception details in c#

WebException is a good approch to get the Real cause of 500 error,  


catch (WebException ex)

{
    using (var stream = ex.Response.GetResponseStream())
    using (var reader = new StreamReader(stream))
    {
        Console.WriteLine(reader.ReadToEnd());
    }
}
catch (Exception ex)
{
    // Something more serious happened
    // like for example you don't have network access
    // we cannot talk about a server exception here as
    // the server probably was never reached
}

Thursday, January 11, 2024

Some Key to Help for Sql Optimization

 Below having some command used to get/analysis the Sql Query for optimization.

Add Below list of command at top pf the Query with ON and at the end again reset with OFF

Ex: Set NoCount ON

--Query

Set NoCount OFF

----Set Of Commands--------

Set NoExec OFF

Set ParseOnly OFF

Set Concat_Null_Yields_NULL OFF

Set Arithabort OFF

--Set Showplan_Text OFF

Set Statistics Time OFF

Set Statistics IO OFF

Set NOCount OFF


-----Mainly Used below three command only-----

SET NOCOUNT ON

SET STATISTICS TIME ON

set statistics io on

Friday, November 10, 2023

Configure React/NodeJS/ExpressJS App in IIS, Configure React in Windows,

 Step 1: Create your Node (Express) backend

Install node

Download exe from Node site and installed.

Restart the Visual Code application

Drag the Folder in application(Target Folder)

open Terminal

Type npm init -y       (This commond initilise the project and add 1 packge.json file into application)

Type npm i express      (This command to install express js)

create a folder name with server in same directory

create a file name with /server/index.js

copy the given file on /server/index.js file

After Installation of express js to run the application add the script start with associated file

Type npm start (This command will run the application)


Step 2: Create an API Endpoint

Write you code in /server/index.js

Type npm start (This command will run the application)


Step 3: Create your React frontend

Create Client Project

Type npx create-react-app client (Client means name of the project)

for testing purpose add proxy setting on client /client/package.json

go to inside client folder to run the application

Type npm start (This command will run the application)


Step 4: Make HTTP Requests from React to Node

Write Client code request in /client/src/App.js

Type npm start (This command will run the application)

Type npm run build (This command build the application this folder can be confiugure in IIS)


Step 5: Deploy your app on local inside

1. Here for deployement Client and Server i create two application on IIS

2. Client Application (React) create an App Pool with V4.0..

3. No Need to Type write npm start in terminal window, this will work after iis configuration

4. Type npm run build command to buuild the application

5. After build the application Point this location on IIS for Client Application For me i used port (localhost:8080)

6. Client Application ready and you can access without any issue

-----------------------------------------------------------------

7. Server Application (Express Js) create an App pool with Not Managed Code

8. Configure Express js is very TDS task, before configure the application need to check.

9. Weather URL Rewrite(URL Rewrite extension) is installed on not on your server, because Express Js required Reverse Proxy.

10. Reverse Proxy will available on Url Rewrite after Installing ARR (Application Request Routing extension)

11. Before Configure NodeJS/ExpressJs on IIS, create a web.config file on Root directory and copied below text init.

    <configuration>

        <system.webServer>

            <rewrite>

                <rules>

                    <rule name="ReverseProxyInboundRule1" stopProcessing="true">

                        <match url="(.*)" />

                        <action type="Rewrite" url="http://localhost:5057/{R:1}" />

                    </rule>

                </rules>

            </rewrite>

        </system.webServer>

    </configuration>

12. After copied config changes add Reverse proxy rule and set the IP with port number for Forwarding request as per my request i.e. localhost:5057

13. Now confiure the Server on IIS and map to Root directory. In my case i used localhost:8081

14. Now i can access both application like

    Client : http://localhost:8080

    Server : htto://localhost:8081  (Due to Reverse Proxy every Request forward to localhost:5057)


Above Sample Project create with help of below site Hosting did by my own

https://freecodecamp.org/news/how-to-create-a-react-app-with-a-node-backend-the-complete-guide/



Tuesday, October 31, 2023

Logical SQL query processing order of query clauses



1 FROM (Joins if available)
2 WHERE 
3 GROUP BY 
4 HAVING 
5 SELECT
    5.1 SELECT list
    5.2 DISTINCT
6 ORDER BY  

7 TOP / OFFSET-FETCH