Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# -- How To Properly Hash A Password (String)

I am currently working on a Form Application in C# that has a login system where users must input their username and password to use the program. These user accounts are stored in an XML file and are currently stored in plain text (I am only in the prototype stage). I am looking for a way to hash the passwords (and maybe the usernames) then store them in the XML file.

I have already done some research into this, but every time I do another search, I find a different way of encrypting a sting. Some ways were able to encrypt and decrypt the string while others are only able to encrypt the string. I am trying to find what will work best for my situation.

For my code, I only need to hash the passwords. This will help keep them more secure to my understanding. I can apparently just hash the password on login and then compare so decrypting isn't a real issue. Also, the process needs to work on any computer. I've seen some answers which only work on a single machine, I am looking for something that is cross-machine compatible if possible. Another thing is, the output of the hashing must be able to be serialized to an XML file without much reworking of the code used to write to the XML file. Currently I am using an XMLSerializer and a StreamWriter to write to the XML file.

Again, I've seen many ways to encrypt or hash a password but I am relatively new to encrypting and hashing stuff so I do not know a good way to do this. Any help will be greatly appreciated and if need be I can add some sample code.

like image 627
Josh H Avatar asked Sep 16 '25 02:09

Josh H


2 Answers

  1. You should generate random string called "salt"
  2. Combine your plain password string with salt and hash result

IN DETAILS:

  1. Generate a long random salt. Note: salt must be different for every login-pass pair!
  2. hash = sha(salt + password) //pseudocode
  3. Save hash and salt in your file

When login:

  1. Calculate hash again. hash = sha(salt_in_file + password_input)
  2. Compare hash with your hash_in_file

And don't use MD5! Better look here Also look through this article

UPDATE: Ok, maybe this approach is not good enough. If you want really strong security you should use special slow hashing algorithm. Some of them already maintain salt. I don't claim to be specialist in cryptography. Never rely on single opinion in this area.

Anyway, the above should be enough in many cases.

like image 199
shameleo Avatar answered Sep 17 '25 17:09

shameleo


Proper way to hash a password is to use a specialized function like bcrypt or scrypt.

like image 37
DarkWanderer Avatar answered Sep 17 '25 16:09

DarkWanderer