Introduction
Normally, web developers do not take keen interest to secure the query string and connection string information which usually reside in the registry and the user passwords which reside in the user registration database table. When I was creating a web-based application in ASP.NET, I decided to use these three encryptions to fully secure my application.
.NET provides us the new Cryptography classes to encrypt and decrypt the data whenever used.
I would like to discuss these three issues one by one.
Encrypt Password field in SQL Server
This is the a common practice of developers, not to encrypt the user-login passwords in the database table fields. If anyone has access to the database tables, he can easily use these passwords to enter into the site anytime. So to avoid this situation, I used, .NET�s Cryptography classes.
The business logic which I used is that, when a user is added through my web application, on form submit event, I first get the user�s information from the form fields, encrypt the employee�s password and then submit the entire information into the user registration table. The password information is encrypted in the user registration table. Now, when the user enter into the application, provides userid and password, I just encrypt the user provided password and match it with the employee table�s password, so I don�t need to decrypt the database stored password again and again.
Encrypt Registry Information in SQL Server
Typically, most of the developers including me think that the windows registry is the best place to store key information like connection strings. But these information in the registry are not encrypted and if anyone has access to the server he can easily get all the secure information including the database passwords etc. To avoid this situation also, I use .NET�s Cryptography classes to save the key information residing in the registry.
Encrypt Query String
Often developers pass information from one page to another by using query string, without encrypting those sort of information. Let�s take a scenario where (e.g. it is necessary to encrypt the information contained in the query) I pass the area name (e.g. TownId) from one to another page and on the basis of that TownId I want to get some information from the database. If the user change the TownId in the address bar of the browser and refresh the web page, then this changed TownId will pass and the information related to the users changed TownId will be viewed. So by doing this, the user is able to get all the towns' information whether he has access to all the other towns' information or not.
By the .NET�s Cryptography classes, we can send these information first by encrypting and after receiving, do the reverse process, i.e. to decrypt and use that information.
I have made a class named Utilities and imported the following classes,
Imports System
Imports System.IO
Imports System.Xml
Imports System.Text
Imports System.Security.Cryptography
Two public shared functions named EncryptText and DecryptText with one argument of type string are made.
From an ASP.NET page, just provide the text that you want to encrypt/decrypt into this function and it will return you an encrypted/decrypted text depending upon the function you use.
The EncryptText function internally uses the Encrypt function which uses two parameters: one is the user�s text and other is the encryption which must be on eight digit code. Same as the case for DecryptText function, it uses Decrypt function.
The source code for the function is given below:
Public Shared Function EncryptText(ByVal strText As String) As String
Return Encrypt(strText, �&%#@?,:*")
End Function
'Decrypt the text
Public Shared Function DecryptText(ByVal strText As String) As String
Return Decrypt(strText, "&%#@?,:*")
End Function
'The function used to encrypt the text
Private Shared Function Encrypt(ByVal strText As String, ByVal strEncrKey _
As String) As String
Dim byKey() As Byte = {}
Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
Try
byKey() = System.Text.Encoding.UTF8.GetBytes(Left(strEncrKey, 8))
Dim des As New DESCryptoServiceProvider()
Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(strText)
Dim ms As New MemoryStream()
Dim cs As New CryptoStream(ms, des.CreateEncryptor(byKey, IV),_
CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)
cs.FlushFinalBlock()
Return Convert.ToBase64String(ms.ToArray())
Catch ex As Exception
Return ex.Message
End Try
End Function
'The function used to decrypt the text
Private Shared Function Decrypt(ByVal strText As String, ByVal sDecrKey _
As String) As String
Dim byKey() As Byte = {}
Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
Dim inputByteArray(strText.Length) As Byte
Try
byKey = System.Text.Encoding.UTF8.GetBytes(Left(sDecrKey, 8))
Dim des As New DESCryptoServiceProvider()
inputByteArray = Convert.FromBase64String(strText)
Dim ms As New MemoryStream()
Dim cs As New CryptoStream(ms, des.CreateDecryptor(byKey,_
IV), CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)
cs.FlushFinalBlock()
Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
Return encoding.GetString(ms.ToArray())
Catch ex As Exception
Return ex.Message
End Try
End Function
Conclusion
I have shown here the three main areas where you should use encryption mechanism to secure your web-application. If you have any query or difficulty to implement it, please feel free to email me at: adnanahmed235@yahoo.com.
|
|
 |
 | why does my encrypted string always end with '=' [modified] olibenu | 8:33 11 Jan '10 |
|
 |
my results always end with the equal sign (=). why is that?
modified on Friday, January 15, 2010 1:17 PM
|
|
|
|
 |
 | error prabupep | 21:59 6 Jan '10 |
|
 |
hi its really nice one !
when am using this its giving me a exception lik Specified key is not a valid size for this algorithm.
|
|
|
|
 |
 | How do you protecting the code Member 2112497 | 6:53 10 Feb '09 |
|
 |
The techniques mentioned do indeed protect the passwords in the database but how do you stop someone using reflection to see what your key and / or salt value is? Would the obfuscator do a good enough job?
|
|
|
|
 |
 | Error mrichar3 | 7:30 14 Nov '08 |
|
 |
When i try to build i get the following error, Number of indices is less than the number of dimensions of the indexed array, for the highlighted line...
'The function used to encrypt the text Private Shared Function Encrypt(ByVal strText As String, ByVal strEncrKey _ As String) As String Dim byKey() As Byte = {} Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
Try byKey() = System.Text.Encoding.UTF8.GetBytes(Left(strEncrKey, 8))
Dim des As New DESCryptoServiceProvider() Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(strText) Dim ms As New MemoryStream() Dim cs As New CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write) cs.Write(inputByteArray, 0, inputByteArray.Length) cs.FlushFinalBlock() Return Convert.ToBase64String(ms.ToArray())
Catch ex As Exception Return ex.Message End Try
End Function
|
|
|
|
 |
|
 |
Sorry... i see that this error was already addressed.
|
|
|
|
 |
 | Thank you m-chaos | 17:59 18 Feb '08 |
|
|
 |
 | Error Naderrafiee | 22:47 6 Jan '08 |
|
 |
Hi When i run this code i get folowing err in Decrypt Function Bellow Line: Line has err: InputByteArray=Convert.FromBase64String(StrText) Error:Invalid length for base-64 char array
Thanks
|
|
|
|
 |
|
 |
how can i solve this error !! it appeared also with me
Eng.Mohammed Ramadan Al-Ashry
|
|
|
|
 |
 | Two other related encryption articles in CodeProject ... Tony Selke | 7:56 27 Sep '07 |
|
 |
You may also be interested in looking at the following, related Code Project articles:
Generic SymmetricAlgorithm Helper[^] This is a generic helper class that exposes simplified Encrypt and Decrypt functionality for strings, byte arrays and streams for any SymmetricAlgorithm derivative (DES, RC2, Rijndael, TripleDES, etc.).
Making TripleDES Simple in VB.NET and C#[^] This is a simple wrapper class that provides an easy interface for encrypting and decrypting byte arrays and strings using the 3DES algorithm.
|
|
|
|
 |
 | Excellent Code SeaCrab | 6:57 25 Jun '07 |
|
 |
Worked from the first time.
|
|
|
|
 |
 | Encrypt and Decrypt in ASP.NET using C# sssabi | 2:14 16 May '07 |
|
 |
Can anybody tell me how to Encrypt and Decrypt a Text using C#.Net.I"m using C# in my ASP.NET Website. I'll be very thankful to you.
satheesh
|
|
|
|
 |
|
 |
Hi! This worked for me:
public static string EncryptText(string strText) { return Encrypt(strText, "&%#@?,:*"); }
// Decrypt the text public static string DecryptText(string strText) { return Decrypt(strText, "&%#@?,:*"); }
// The function used to encrypt a string private static string Encrypt(string strText, string strEncrKey) { byte[] byKey; byte[] IV = { 18, 52, 86, 120, 144, 171, 205, 239 }; try { byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = Encoding.UTF8.GetBytes(strText); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); return Convert.ToBase64String(ms.ToArray()); } catch (Exception ex) { return ex.Message; } } // The function used to decrypt the string private static string Decrypt(string strText, string sDecrKey) { byte[] byKey; byte[] IV = {18, 52, 86, 120, 144, 171, 205, 239}; byte[] inputByteArray; // inputByteArray.Length = strText.Length; try { byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); inputByteArray = Convert.FromBase64String(strText); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); System.Text.Encoding encoding = System.Text.Encoding.UTF8; return encoding.GetString(ms.ToArray()); } catch (Exception ex) { return ex.Message; } }
**********************
and:
<asp:Button ID="btnEncStr" runat="server" OnClick="btnEncStr_Click" Text="Encode string" />
<asp:TextBox ID="txtEncStr" runat="server">
<asp:Button ID="btnDecStr" runat="server" OnClick="btnDecStr_Click" Text="Decode string" Width="123px" />
|
|
|
|
 |
|
 |
Awesome Code. Thanks a lot.
Narinder Sharma
|
|
|
|
 |
|
 |
hey man... pretty cool
thanks a lot!
|
|
|
|
 |
 | Querystring issue inspoiehfkdbc | 6:46 26 Apr '07 |
|
 |
The code looks good and is of great help.
The problem that I am having is that I am using your code to encrypt the ID that is passed in querystring . The encrypted string for some id's have "+" and "/" in that . It creates problems for in certain cases . For example "7003" is encrypted as "/o4s0R+vqeg=" Is there a way to get rid of "/" ,"+" etc etc ?
Thanks in advance.
|
|
|
|
 |
|
 |
Did you find an answer to your problem ?
I use this code - I found it elsewhere:
Instead of using the special characters to encrypt “&;%#@?,:*"- use regular characters - like abcdefg1234
|
|
|
|
 |
 | Great job, worked the first time johndsc | 1:18 23 Mar '07 |
|
 |
However I had to remove the parentheses after byKey: Dis not work: byKey() = System.Text.Encoding.UTF8.GetBytes(Left(strEncrKey, 8)) Worked: byKey = System.Text.Encoding.UTF8.GetBytes(Left(strEncrKey, 8))
Steve Davis
|
|
|
|
 |
 | Pretty good one. r_maiya | 8:50 19 Mar '07 |
|
 |
I was looking for some simple encryption, all the examples I used to see is Hashing but your example made my life easier.
|
|
|
|
 |
 | Good one! CharuT | 20:05 8 Nov '06 |
|
 |
Good one there. Appreciate that. Thank you!
Charu.
|
|
|
|
 |
|
 |
Rated Excellent.
Charu.
|
|
|
|
 |
 | Problems about RSA Password encryption puriamrik | 3:47 10 Oct '06 |
|
 |
Thanks in advance. SqlConnection con = new SqlConnection(); con.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
if (con.State == ConnectionState.Closed) { con.Open(); } byte[] byteData = Encoding.ASCII.GetBytes(password);
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
byte[] encData = rsa.Encrypt(byteData, false); Label4.Text = Encoding.ASCII.GetString(encData); SqlCommand cmd1 = new SqlCommand(); cmd1.Connection = con; cmd1.CommandText = "insert into Users values('a','" + Encoding.ASCII.GetType(encData) + "','a@a.com')"; cmd1.ExecuteNonQuery(); cmd1.Dispose();
my database field is varbinary(50).
i'm getting problem in saving this into databaes. can u plz help me.
---Puri
|
|
|
|
 |
 | You made a excellent job britneyssssers | 11:32 29 Aug '06 |
|
 |
Thanks a ton, this source code is so usefull, an i really aprecciate that guy who post the C# version
ff
|
|
|
|
 |
 | thanks yusufziya | 1:04 10 Aug '06 |
|
 |
Thanks for this article .Good job
Yusuf Ziya Keskinsoy
|
|
|
|
 |
 | Can you call this from SQL? ja928 | 12:41 2 Aug '06 |
|
 |
I have utilized this technique and it works great, thanks! My only drawback is that I need to put the encrypted field onto a Crystal Report populated directly from a stored procedure. I've seen methods for populating the report with a dataset (I could then call Decrypt there) but it doesn't fit with the architecture of our reports. I've also seen code which allows calling a VB dll from SQL with sp_OACreate, but I am trying to find the best way to do this. Is there a way to port this code to a SQL User defined function?
To understand recursion, you must first understand recursion.
|
|
|
|
 |
 | Tanx GayuDam | 1:20 23 Jun '06 |
|
|
 |
|
|
Last Updated 14 Jan 2003 |
Advertise |
Privacy |
Terms of Use |
Copyright ©
CodeProject, 1999-2010