1

I am trying to store hashed password in sql express database. but I am not able to do that one. Here is my code:

SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();

byte[] encode = sha.ComputeHash(Encoding.ASCII.GetBytes(pass));

string cmd = "insert into tblLogin (username,password,email,state,active) values ('"+name+"',"+encode+",'"+email+"','"+state +"',"+ active + ")" ;

And in database I kept password as varbinary.

Here my problem is I am getting value of encode as System.Byte[] but not hashed value. How can I do this, I tried to find and I am getting how to hash password but not how to store password.

Here my main problem is How can I construct Insert query and store Byte[] into database?

martinstoeckli
  • 23,430
  • 6
  • 56
  • 87
user1782698
  • 33
  • 1
  • 6
  • Read this, you need cast the value... http://stackoverflow.com/questions/9067470/sql-query-to-store-text-data-in-a-varbinarymax – Mate Dec 07 '12 at 05:19
  • 2
    Passwords should really be salted as well. In fact, why not just use the `System.Web.Helpers.Crypto.HashPassword(password)` which will automatically salt the password and make it cryptographically strong? – Erik Funkenbusch Dec 07 '12 at 05:21
  • @MystereMan : I am happy to do that, but afterwards how can I compare it with user input's password or retrieve password in case of Password recovery? I tried to do this but I am not able to locate ...Helpers namespace. – user1782698 Dec 07 '12 at 05:23
  • @user1782698 - You can't recover hashed passwords. They're one way. That's the point of hashing. http://msdn.microsoft.com/en-us/library/system.web.helpers.crypto(v=vs.111).aspx (if you notice there is also a VerifyHashedPassword function) – Erik Funkenbusch Dec 07 '12 at 05:31
  • Yes. This is why proper site never have passsword recovery like this - they can generate a new password for you, but never recover the old one. – TomTom Dec 07 '12 at 06:01
  • Instead of using a fast hashing algorithm, you better use a slow key derivation function like PBKDF2 or BCrypt to hash passwords. CSharp has built-in support for [PBKDF2](http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes.aspx). – martinstoeckli Dec 07 '12 at 08:50

2 Answers2

3

Save it as a varchar, not varbinary.

Steven Moseley
  • 15,871
  • 4
  • 39
  • 50
3
var provider = new SHA1CryptoServiceProvider(salt);
byte[] bytes = Encoding.UTF8.GetBytes(input);
string result = Convert.ToBase64String(provider.ComputeHash(bytes)); // store it
abatishchev
  • 98,240
  • 88
  • 296
  • 433