Page 1 of 1

Encryption Technique to Store Sensitive Information in Database

#1 Ninjato  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 6
  • View blog
  • Posts: 29
  • Joined: 24-February 11

Posted 21 March 2011 - 05:35 AM

Hello all, This is my first tutorial on DIC about how to store sensitive information like passwords to your database. The encryption technique I am using here is MD5 Cryptographic Hash Function with a 16 byte Hash Value and converting the bytes to a readable hexdecimal string.

NOTE: [This encryption technique is a one way technique means you can encrypt the string but you cannot decrypt it back to it's original form, So for password recovery you can either send the reset link to the user's email address or you can ask the Security Question. For authentication password will be compared on the basis of Hash Values]

Following are the tools I've used:-
  • Visual Studio 2008 Professional Edition
  • Microsoft SQL Server 2005 Management Edition


First I created my database "HashDB" and then table as "utable" with columns 1. uname (primary key) 2. upwd.
Posted Image
and this is the table

Posted Image

Now, moving on to Solution Explorer, I've taken 3 .aspx pages:-
  • Default Page (This page is used to register user)
    Posted Image

  • Login Page (This page is used to login)
    Posted Image

  • Home Page (This page is used as Home Page on successful login). On PageLoad event of this page I've retrieved the Session that is why it is kept blank and I haven't used any image

Now, I've created a Class File named as "HashString" in App_Code directory of my website. This class will be used to hash the input string and return the encrypted version of the string
There will be two namespaces through which we'll implement our security module;-
  • System.Text
  • System.Security.Cryptography


I've created a static function "CalculateHash" that will take string as argument and return the same.
using System.Text;
using System.Security.Cryptography;

public class HashString
{
    #region Calculate Hash
    public static string CalculateHash(string str)
    {
        byte[] originalBytes, encryptedBytes;
        MD5 md5 = new MD5CryptoServiceProvider();
        originalBytes = ASCIIEncoding.Default.GetBytes(str);
        encryptedBytes = md5.ComputeHash(originalBytes);
        str = BitConverter.ToString(encryptedBytes);
        return str;
    }
    #endregion
}


The "str" string variable will be our password and now, we've declared two byte array as "originalBytes", "encryptedBytes". MD5 class variable is initialized by the constructor of MD5CryptoServiceProvider. ASCIIEncoding class is used to get the bytes from the string "str" and store them into "originalBytes" array. Now, the main view, ComputeHash is an instance method is called through the md5 object and given the arguments as byte array i.e. "originalBytes" and is stored into the byte array "encryptedArray". Finally, with the use of BitConverter class it's static method ToString() is called to convert the byte array "encryptedBytes" into hexadecimal string.

Now, back to Default page where users will get registered . This the code of "SUBMIT" button:
using System.Security.Cryptography;
using System.Text;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["server"].ConnectionString);

    protected void submit_Click(object sender, EventArgs e)
    {
        string uname = TextBox1.Text;
        string upwd = HashString.CalculateHash(TextBox2.Text);

        try
        {
            string sql = "insert into utable(uname, upwd) values(@unameParam,@upwdParam)";
            var cmd = new SqlCommand(sql, cn);
            cmd.Parameters.AddWithValue("unameParam", uname);
            cmd.Parameters.AddWithValue("upwdParam", upwd);
            cn.Open();
            cmd.ExecuteNonQuery();
            Response.Write("Record Inserted");
        }
        catch (Exception ex)
        {
            Response.Write("ERROR " + ex.ToString());
        }
        finally 
        {
            cn.Close();
        }
    }
}



same thing, we've to use two namespaces as System.Text, System.Security.Cryptography. Now, I've stored my connection string in web.config file as
<connectionStrings>
        <add name="server" providerName="System.Data.SqlClient" connectionString="Data Source=.;Initial Catalog=HashDB;Integrated Security=True;Pooling=False"/>
  </connectionStrings>



I've stored the values of our both text boxes in two string variables as "uname" and "upwd" which are user id and password respectively. But, notice we haven't stored the password directly rather the control is transferred to Class HashString in App_Code by calling it's static method CalculateHash with arguments as string which is password from the textbox. After performing all the hashing functionalities the CalculateHash method returns the string value and stores it in "upwd" variable. To store the row into the database table a normal insertion is performed.

Login Page, "LOGIN" button code:
using System.Data.SqlClient;
using System.Security.Cryptography;

public partial class Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["server"].ConnectionString);

    protected void Button1_Click(object sender, EventArgs e)
    {
        string uname = TextBox1.Text;
        string upwd = HashString.ComputeHash(TextBox2.Text);
        try
        {
            string sql = "select uname, upwd from utable where uname = @unameParam and upwd = @upwdParam";
            var cmd = new SqlCommand(sql, cn);
            cmd.Parameters.AddWithValue("@unameParam", uname);
            cmd.Parameters.AddWithValue("@upwdParam", upwd);

            cn.Open();
            var dread = cmd.ExecuteReader();
            if (dread.HasRows)
            {
                dread.Read();
                    //Create Cookies / Sessions
                Session.Add("id", dread["uname"].ToString());
                Response.Redirect("Home.aspx");
            }
            else
            {
                Response.Write("Invalid Username/Password");
            }
            
        }
        catch (Exception ex)
        {
            Response.Write("ERROR: " + ex.ToString());
        }
        finally
        {
            cn.Close();
        }
    }
}



For authentication purpose we'll compute the hash of the password given by the user and a matching password will be find out in the database table by the use of SELECT Query. if authenticated then SqlDataReader wll be used to retrieve the id, store it in Session for state management and redirect to Home Page. Finally, on the page load event of this page I've retrieved the Session for authorization.
protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["id"] != null)
            Response.Write("Hello, " + Session["id"].ToString());
        else
            Response.Redirect("Login.aspx");
    }


I hope my tutorial helped you, Good Luck :shuriken:



Is This A Good Question/Topic? 0
  • +

Replies To: Encryption Technique to Store Sensitive Information in Database

#2 Core  Icon User is offline

  • using System.Linq;
  • member icon

Reputation: 774
  • View blog
  • Posts: 5,097
  • Joined: 08-December 08

Posted 03 April 2011 - 01:52 AM

There is a big problem with MD5, specifically it is prone to the fast collision attack. SHA1 is considered to be a better alternative for now.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1