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:
- The encryption can be performed in an unlimited number of devices.
- It helps ensure the security of your data during remote work and enhances its overall integrity.
- A strong encryption key will prevent hacks and other attacks on your web application.
- 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 |
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.
1 2 3 |
<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:
<RSAKeyValue><Modulus>{RandomString}Modulus><Exponent>AQAB</Exponent></RSAKeyValue>
Private Key :
<RSAKeyValue><Modulus>{RandomString}</Modulus><Exponent>AQAB</Exponent><P>6iXwohRSA7K3jxR8tA0dTFega1NTF/u/gpNfg3ozJ6Gsj20Udeh14JE+XHTyAFH23O9YN001qzfVDIlJcRkHfmsMe4EMVUlijb3Q+kcF5579v8chb2GMVLlgK67VAZ7E7LCfcDIsd/hmjPtnMiOhDNBDWR03ViGM8P5ypXDKOMM=</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ue>
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.
1 2 3 4 5 6 7 8 9 10 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
$("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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
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.