Issam Issam -4 years ago 95
C# Question

Password encryption with SHA1 gives weird output

So I was coding a simple login registration windows app on visual studio as I wanted to start learning again C#
I have this registration page with a few fields, the code is very simple, I didn't do anything related to validation.
I am basically trying to hash the password using SHA1 in c# and output in another textbox, but I am a getting some unknown characters

Here is my code

private void button1_Click(object sender, EventArgs e)
if (username.Text.Trim()=="" || password.Text=="" || passwordc.Text=="" || fname.Text == "" || lname.Text == "" || birthday.Text == "")
MessageBox.Show("Please fill all the fields!");

else if (password.Text!=passwordc.Text) {
MessageBox.Show("Passwords don't match !");

String passwd="";
passwd = password.Text;

byte[] bytes = System.Text.Encoding.UTF8.GetBytes(passwd);
SHA1 sha = new SHA1CryptoServiceProvider();
byte[] passbyte = sha.ComputeHash(bytes);
string pass = System.Text.Encoding.UTF8.GetString(passbyte);
textBox1.Text = pass;


Is there anything wrong or is this a normal hashing? I am kinda confused now.


Answer Source

The hash is just a bunch of bytes. They're not meaningful characters. If you want to turn the hash into a textual form, you can use Convert.ToBase64String():

string pass = Convert.ToBase64String(passByte);

Also, consider switching to SHA256. SHA1 is becoming easier and easier to crack as computing power increases. One common thing to do is to run the hashing process (the new hash becomes the password to hash) hundreds or thousands of times before storing it. It doesn't make too significant a difference in time for creating a hash to store, but it makes cracking the password take that many times longer.

Also, you'll want to start incorporating a random salt to each password to hash. This avoids rainbow table attacks and won't generate the same hash for identical passwords.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download