Thursday, April 7, 2011

Hashing In C#

Problem
It is a common practice to save the user and the password associated with the user as a plain text in the database, but there is one problem with this approach, your passwords are not secure, anyone one who has an access to the database can steal your data. How to make sure that your password is secure.

Impact
Data is not secure.

Solution
 To make sure that password or any kind of data you passing is secure we use a process called Hashing. In C# we could used MD5 or SHA1 Hashing. Following is an example of how to create a hash for a password that user entered in the textbox.




namespace PasswordEncription
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string password = PassWordTextBox.Text;
            byte[] buffer = GetCharArray(password);
            ResultTextBox.Text = EncriptPassword(buffer);
        }

        private byte[] GetCharArray(string password)
        {
            byte[] buffer = new byte[password.Length];
            int i = 0;
            foreach (byte c in password)
            {
                buffer[i] = c;
                i++;
            }
            return buffer;
        }

        private string EncriptPassword(byte[] password)
        {
            MD5CryptoServiceProvider encriptor = new MD5CryptoServiceProvider();
            byte[] encriptedPassword = encriptor.ComputeHash(password);
            StringBuilder stringBuilder = new StringBuilder();
            foreach (sbyte b in encriptedPassword)
            {
                stringBuilder.Append(b.ToString("x2"));
            }
            return stringBuilder.ToString();
        }
    }
}

1 comment: