2

I am designing a C# application in which I need to store users' login information, including their passwords, in a database table. I was wondering what's a decent way of doing this.

I know it is a terrible idea to store passwords as clear text.

I was thinking of encrypting the passwords and then storing them. After that, every time the users enter their passwords, I can encrypt their input and compare that encrypted input with the one already in the database. My plan is to use a good has function for the encryption...

temelm
  • 826
  • 4
  • 15
  • 34
  • possible duplicate of [Preferred Method of Storing Passwords In Database](http://stackoverflow.com/questions/615704/preferred-method-of-storing-passwords-in-database) – PaulG Feb 26 '12 at 23:06
  • Note that the top few answers in the duplicate do not address iterating the hash: this is very important because it is still easy to brute-force alphanumeric passwords with a single hash iteration, even if they are salted. – Cameron Skinner Feb 26 '12 at 23:08
  • @Cameron. I wouldn't really say brute forcing a single iterated salted hash is 'easy' for any modern algorithm. Regardless, its *this* q&a that is the duplicate. You might want to repost your answer into the original thread if it's something you feel needs clarifying. – PaulG Feb 26 '12 at 23:32

2 Answers2

5

Never store the password. Store a hash of the password.

Note that this is not encryption. Hashing and encrypting are related, but they are not the same.

The best thing you can do is use a standard password hashing function such as bcrypt or pbkdf2. Don't reinvent the wheel.

This article has an excellent description of how to store passwords securely.

Cameron Skinner
  • 51,692
  • 2
  • 65
  • 86
5

I think a common tactic is to make a hash of the password using something like SHA-256 and storing that in the database. Then to log in, you hash whatever the user enters and compare it with what is in the database.

This systems means that your "encryption" is one way. You cannot retrieve the password given the password hash. Note that this has usability consequences. Specifically, you cannot send users their password. You can only reset passwords.

A further improvement would be to salt the password before you hash it. This prevents a class of attacks involving rainbow tables. You should almost certainly do this as well as hashing the password.

As mentioned by other people, it is also important to iterate this several times to prevent brute-force attacks.

Oleksi
  • 12,947
  • 4
  • 56
  • 80