Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How To Do End To End Data Encryption & Decryption in Asp.net Web Form

Encryption is a process that involves translating your text, documents, images, videos, and other data into gibberish data that cannot be understood by any human or machine. It only becomes readable after decryption which translates the random gibberish data back to its original state. This method can only be performed by someone who knows the exact way to decrypt the data and it often involves a key. Encryption and decryption become very useful when dealing with web applications that are hosted on the client side. As such, the encryption process can help maintain the security of your user’s data.

There are several benefits of encryption and decryption using ASP.Net. These are:

  1. The encryption can be performed in an unlimited number of devices.
  2. It helps ensure the security of your data during remote work and enhances its overall integrity.
  3. A strong encryption key will prevent hacks and other attacks on your web application.
  4. Encryption will also prevent identity theft and help keep you anonymous online.

In this blog, our DEV IT engineers have explained the steps needed to perform encryption and decryption in ASP.Net web forms for your web applications. The steps in doing so are:

1.) First of all, we need the javascript files listed below for the Client side to encrypt the content.

  • System.debug.js
  • System.IO.debug.js
  • System.Text.debug.js
  • System.Convert.debug.js
  • System.BitConverter.debug.js
  • System.IO.BinaryReader.debug.js
  • System.BigInt.debug.js
  • System.Security.Cryptography.SHA1.debug.js
  • System.Security.Cryptography.debug.js
  • System.Security.Cryptography.RSA.debug.js

2.) Next, we’ll need the class mentioned below for server side decryption and other functionality.

public class EncryptionPageDataProvider : LibCommon.PageBase
    {
        public static string privateKey;
        public static string publicKey;
        public static RSACryptoServiceProvider rsa;
        public static string UserName = "";
        public static int saltLengthLimit = 32;
        
        //The function mentioned below is used to assign required parameter 

        public static void AssignParameter()
        {
            const int PROVIDER_RSA_FULL = 1;
            const string CONTAINER_NAME = "KeyContainer";
            CspParameters cspParams;
            cspParams = new CspParameters(PROVIDER_RSA_FULL);
            cspParams.KeyContainerName = CONTAINER_NAME;
            cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
            cspParams.ProviderName = "Microsoft Strong Cryptographic Provider";
            rsa = new RSACryptoServiceProvider(cspParams);
            rsa.PersistKeyInCsp = false;
        }


//The function mentioned below is used to assignor generate new public and private key 

        public static void AssignNewKey()
        {
            AssignParameter();
            RSA rsa = new RSACryptoServiceProvider(2048);
            string PrivateKeyXML = rsa.ToXmlString(true);
            privateKey = PrivateKeyXML; // sets the new private key.

            string publicOnlyKeyXML = rsa.ToXmlString(false);
            publicKey = publicOnlyKeyXML; // sets the new public key.
            LibCommon.LibResult res = new LibCommon.LibResult();
            DataProviders.EncryptionPageDataProvider.UpdateNewKeys(publicOnlyKeyXML, PrivateKeyXML);
            if (res.HasError)
            {
                throw new Exception(res.ErrorException.Message);
            }
        }

//The function mentioned below is used encrypt data with salt string

        public static string EncryptData(string data2Encrypt, string salt)
        {
            LibCommon.LibResult res = new LibCommon.LibResult();
            try
            {
                AssignParameter();
                

                res = GetKeys(UserName);
                if (res.HasError)
                {
                    return "";
                }
                else
                {
                    rsa.FromXmlString(res.ResultDS.Tables["tblKeys"].Rows[0]["PublicKey"].ToString());
                    //read plaintext, encrypt it to ciphertext
                    byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data2Encrypt + salt);
                    byte[] cipherbytes = rsa.Encrypt(plainbytes, false);
                    return Convert.ToBase64String(cipherbytes);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(res.ErrorException.Message);
            }
            
        }

//The function mentioned below is used encrypt data without salt string
        public static string EncryptData(string data2Encrypt)
        {
            LibCommon.LibResult res = new LibCommon.LibResult();
            try
            {
                AssignParameter();
                
                res = GetKeys(UserName);
                if (res.HasError)
                {
                    return "";
                }
                else
                {
                    rsa.FromXmlString(res.ResultDS.Tables["tblKeys"].Rows[0]["PublicKey"].ToString());
                    //read plaintext, encrypt it to ciphertext
                    byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data2Encrypt);
                    byte[] cipherbytes = rsa.Encrypt(plainbytes, false);
                    return Convert.ToBase64String(cipherbytes);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(res.ErrorException.Message);
            }

        }
//The function mentioned below is used decrypt the encrypted data without salt string
        public static string DecryptData(string data2Decrypt, string privatekey)
        {
            LibCommon.LibResult res = new LibCommon.LibResult();
            
                AssignParameter();

                byte[] getpassword = Convert.FromBase64String(data2Decrypt);

                string publicPrivateKeyXML = privatekey;
                rsa.FromXmlString(publicPrivateKeyXML);

                //read ciphertext, decrypt it to plaintext
                byte[] plain = rsa.Decrypt(getpassword, false);
                string dataAndSalt = System.Text.Encoding.UTF8.GetString(plain);
                return dataAndSalt;            
        }

//The function mentioned below is used decrypt the encrypted data with salt string 

        public static string DecryptData(string data2Decrypt, string privatekey, string salt)
        {
            LibCommon.LibResult res = new LibCommon.LibResult();

            AssignParameter();
            byte[] getpassword = Convert.FromBase64String(data2Decrypt);
            string publicPrivateKeyXML = privatekey;
            rsa.FromXmlString(publicPrivateKeyXML);

            //read ciphertext, decrypt it to plaintext
            byte[] plain = rsa.Decrypt(getpassword, false);
            string dataAndSalt = System.Text.Encoding.UTF8.GetString(plain);
            return dataAndSalt.Substring(0, dataAndSalt.Length - salt.Length);

        }

//The function mentioned below is used to get public and private key from the table   

        public static LibResult GetKeys(string UserName)
        {
            LibResult res;
            res = new LibResult();
            Database db = DatabaseFactory.CreateDatabase();
            DataSet ds = new DataSet();
            try
            {
                DbCommand cmd = db.GetStoredProcCommand("spGetKeys",UserName);
                cmd.CommandTimeout = 0;
                String[] tblNames = { "tblKeys" };
                db.LoadDataSet(cmd, ds, tblNames);
                res.ResultDS = ds;
            }
            catch (Exception e)
            {
                ds = null;
                res = new LibResult(e, null);
            }
            return res;
        }


        

//The function mentioned below is used to update the new public and private key user wise to table. 

public static LibCommon.LibResult UpdateNewKeys(string PublicKey,string PrivateKey)
        {
            LibResult res = new LibResult();
            Database db = DatabaseFactory.CreateDatabase();

            try
            {
                DbCommand cmd = db.GetStoredProcCommand("spUpdateNewKeys", PublicKey, PrivateKey, UserName);
                db.ExecuteNonQuery(cmd);
            }
            catch (Exception e)
            {
                res = new LibResult(e, null);
            }

            return res;
        }


//The function mentioned below is used to insert the activity of user, login time, sessionId etc.

        public static LibCommon.LibResult InsertIntoBankUserLog(string UserName, string SessionId, bool IsActive,DateTime LogInDateTime,string IpAddress)
        {
            LibResult res = new LibResult();
            Database db = DatabaseFactory.CreateDatabase();

            try
            {
                DbCommand cmd = db.GetStoredProcCommand("spInsertBankUserLog", UserName, SessionId, IsActive, LogInDateTime, IpAddress);
                db.ExecuteNonQuery(cmd);
            }
            catch (Exception e)
            {
                res = new LibResult(e, null);
            }

            return res;
        }


//The function mentioned below is used to track the activity of user, login time, logout time etc.

        public static LibCommon.LibResult UpdateBankUserLog(string UserName,string SessionId, bool IsActive, DateTime LogOutDateTime)
        {
            LibResult res = new LibResult();
            Database db = DatabaseFactory.CreateDatabase();

            try
            {
                DbCommand cmd = db.GetStoredProcCommand("spUpdateBankUserLog", UserName, SessionId, IsActive, LogOutDateTime);
                db.ExecuteNonQuery(cmd);
            }
            catch (Exception e)
            {
                res = new LibResult(e, null);
            }
            return res;
        }

//The function mentioned below is used to generate random salt string every time. 

    public static string getrandomvalue(int size)
        {
            try
            {
                var s = new System.Security.Cryptography.RNGCryptoServiceProvider();
                var buff = new byte[size];
                s.GetBytes(buff);
                return Convert.ToBase64String(buff);
            }
            catch (Exception)
            {

                throw;
            }
        }

3.) Next, you will need two hidden keys filed for public key and for salt String.

<asp:HiddenField ID="PublicKey" runat="server" />
 <asp:HiddenField ID="Salt" runat="server" />

4.) Example of Public key and private key used for encryption and decryption

Public key:

{RandomString}Modulus>AQAB

Private Key :

{RandomString}AQAB

6iXwohRSA7K3jxR8tA0dTFega1NTF/u/gpNfg3ozJ6Gsj20Udeh14JE+XHTyAFH23O9YN001qzfVDIlJcRkHfmsMe4EMVUlijb3Q+kcF5579v8chb2GMVLlgK67VAZ7E7LCfcDIsd/hmjPtnMiOhDNBDWR03ViGM8P5ypXDKOMM=

+yAzMoJ9/k5P9CB5NfnvhTyOWSNhgfTT5GEur09I/f9QM1VL++EpjaKZC5Nce6gjR+OxX7q/5zsZJKqz5i0ZRiS9wMrul0UoqYEc/tG7jr8xDeVsGsIqk+BHHLovUOb6TZjejME9UlwtDwtwniKqTTF54fA6gvCPocUzQ+djtcs=xJvzAMW7UCujAlubkrxoW5BAvZ4L6dmUJ5qD2yyjA6Y39X8MbS0yvcx35r6z7hzlAwNeuaD1bb3GAW7N4k+4ASj2JEZqCrtCK+61KVK13JWeUIhuxM3OPd4iqMt3RJMCnBR67ITU3jAQPFVlg65zLwU5Z/ymWIZ3iGy/67dXtm0=l/lDooSgFP91mWrxj73CuyILj1w/DTOJ7AL4CrXzmWsiMP6krjj0Obe14PB8HoWBXGcqF6HfsuLr82mu11RhoDZp8zucKkV7NyFg18E7PUbtO9iklIj+1WD8CCGQsuglgEJMJGhpYOdRiXJF5B1cbLzNYvNLpaRJd//sZ2Kn0AM=wRnIGMNLG2jW1lL5ZA03SjqHrGPnU9zIHt4xJJO0m3oo5WzSm0rkwp60cutgehWH6igNwOHeZLALZ5VSkno+1rO4wixCxL/OdmcXcMRMQUepkU/x3dmnweNiY8aKGv19k7FCl+KgTJvxWNyk0Cm/45lA0Ray+IAddq4a8NF/fKQ=dr55hcwt1BWvg5FT1MHnGtQdyx0Gp5kO30zroJ7e7O8BBTYkAov57KoRG86bLzmvoyaupof/jGIYc5P0oa0vPy2N7IUboKG3ti2Rz/idfjw7GXMl8t64XRGFeyl/GhUWdawG9kwMa6TLGqrehpj+73nzlz2eHB+b4wUJHcP5Okyo1vobvkh7RD3mM8388TLHaNf/h/b5F+Z8nt2lM9ZeUrCD265uBc/TkiZWbMRHIBdxojtltzECgJqui5GZIy90sIUtZvGAVJh3zUpykYllPz4ixmVWj5pnoxyBx0agOo34bCbsO97BtkgW/Td/mCSpWCADUOUHndz35tGzMVTR9Q==

5.) You can save this key to the table and every time the user logins, it will start a new session, and both of these keys will change and store to the table.

Below is the code that changes both keys every time a new login is performed and saves it with respect to the user.

DataProviders.EncryptionPageDataProvider.UserName = UserName;
                                                        DataProviders.EncryptionPageDataProvider.AssignNewKey();

LibCommon.LibResult res = new LibCommon.LibResult();

SessionIDManager manager = new SessionIDManager();

Session["SessionId"] = manager.CreateSessionID(HttpContext.Current);
                                                        DataProviders.EncryptionPageDataProvider.InsertIntoBankUserLog(UserName, Session["SessionId"].ToString(), true, DateTime.Now, ClientIP);

6.) Assign Public Key and Salt Hidden Field variables

protected void Page_Load(object sender, EventArgs e)
{
            
            LibCommon.LibResult res1 = new LibCommon.LibResult();
            res1 = DataProviders.EncryptionPageDataProvider.GetKeys(this.Page.User.Identity.Name);
            if (res1.HasError)
            {
                throw new Exception(res1.ErrorException.Message);
            }
            else
            {
                PublicKey.Value = res1.ResultDS.Tables["tblKeys"].Rows[0]["PublicKey"].ToString();
                DataProviders.EncryptionPageDataProvider.privateKey = res1.ResultDS.Tables["tblKeys"].Rows[0]["PrivateKey"].ToString();
            }
            this.Salt.Value = DataProviders.EncryptionPageDataProvider.getrandomvalue(DataProviders.EncryptionPageDataProvider.saltLengthLimit);

 }

7.) How we encrypt the content at the client side.

$("body").on("click", "#MainContent_ImageButton1", function (e) {
                encrypt();
            });

function encrypt() {
            var PublicKey = $("[id*=PublicKey]").val();
            var Salt = $("[id*=Salt]").val();
            var KeyNo=$("[id*=txtKeyNo]").val();
            var FormFlag=$("#MainContent_DropDownList1 option:selected").text();
            var FormNo= $("[id*=txtFormNo]").val();
            if (KeyNo != "" || (FormFlag != "" && FormNo != "")) {
                var rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
                rsa.FromXmlString(PublicKey);
                if (KeyNo != "") {
                    var byteKeyNo = System.Text.Encoding.UTF8.GetBytes(KeyNo + Salt);                    
                    var encryptedBytesKeyNo = rsa.Encrypt(byteKeyNo, false);
                    var encryptedStringKeyNo = System.Convert.ToBase64String(encryptedBytesKeyNo);                    
                    $("[id*=txtKeyNo]").val(encryptedStringKeyNo);
                }
                if (FormFlag != "" && FormNo != "") {
                    var byteFormFlag = System.Text.Encoding.UTF8.GetBytes(FormFlag + Salt);
                    var encryptedBytesFormFlag = rsa.Encrypt(byteFormFlag, false);
                    var encryptedStringFormFlag = System.Convert.ToBase64String(encryptedBytesFormFlag);
                    $("[id*=EFormFlag]").val(encryptedStringFormFlag);

                    var byteFormNo = System.Text.Encoding.UTF8.GetBytes(FormNo + Salt);
                    var encryptedBytesFormNo = rsa.Encrypt(byteFormNo, false);
                    var encryptedStringFormNo = System.Convert.ToBase64String(encryptedBytesFormNo);
                    $("[id*=txtFormNo]").val(encryptedStringFormNo);
                }
                return true;

            }
            else {
                $("[id*=txtKeyNo]").val('');
                $("[id*=DropDownList1]").val('');
                $("[id*=txtFormNo]").val('');
                return false;
            }
        }

8.) Here we decrypt that encrypted content at the server side.

protected void btnGetDetail_Click(object sender, EventArgs e)
        {
            try
            {
                
                if (this.txtKeyNo.Text.Trim()!=string.Empty)
                    this.txtKeyNo.Text = DataProviders.EncryptionPageDataProvider.DecryptData(this.txtKeyNo.Text, DataProviders.EncryptionPageDataProvider.privateKey, this.Salt.Value);
                if (this.txtKeyNo.Text.Trim().Length == 0)
                {
                    throw new Exception("Key No should not be blank...");
                }
                else
                {                    
                    LibResult res = this.DisplayData(this.txtKeyNo.Text, "", "", "");
                    if (res.HasError)
                    {
                        throw new Exception(res.ErrorException.Message.ToString());
                    }
                    else
                    {
                        this.TaxDetailPnl.Visible = true;
                        this.lblerr.Text = "";
                    }
                }
                
            }
            catch (Exception Ex)
            {
                this.lblerr.Text = Ex.Message.ToString();
                this.TaxDetailPnl.Visible = false;
                
            }
        }

Conclusion

By following the steps in the blog, you would have learnt the methods and benefits of encrypting and decrypting your data. Now, you can begin securing yourself and your users with an advanced level of data security in a dangerous world of hackers. If you encounter any issues during the process, then feel free to drop a comment below and we will be sure to get back to you.

The post How To Do End To End Data Encryption & Decryption in Asp.net Web Form appeared first on DEV IT Journal.



This post first appeared on DEV IT Journal - Simplifying IT, Empowering Busine, please read the originial post: here

Share the post

How To Do End To End Data Encryption & Decryption in Asp.net Web Form

×

Subscribe to Dev It Journal - Simplifying It, Empowering Busine

Get updates delivered right to your inbox!

Thank you for your subscription

×