1

When I use a hash-function to encrypt the passwords of my users to store them in a database, aren't there an infinite amount of right passwords? Because multiple strings can produce the same hash, right? Is this even safe then?

F.M.F.
  • 1,158
  • 13
  • 33

1 Answers1

3

You are correct. Because hashes are generally shorter than the data they represent, there will be times where two different inputs produce the same hash. We call this a hash collision. To reduce the chances of this choose a better hashing algorithm. Note the standard for what is considered a good hashing algorithm is always changing, check this S.O. post.

It is not safe to store plain hashes in your database for another reason. There are online lists of completed hashes using common hashing algorithms. So you can take one of these lists (called a rainbow table), and the hashed passwords in your database, then work out which hashes correspond to which passwords by doing a simple look up in the rainbow table.

Since many users will pick one of the most common bad passwords (e.g. qwerty), this is a huge problem. The solution to this is called hash and salt. Where you first add a large random string of characters to your password before hashing. Meaning even two of the same passwords result in different hashes in your database. This is better explained here and here.

Generally it as a bad idea to write this code yourself. Try authenticate with another service like Facebook or Google. Their code is likely to be better tested and designed than anything an individual developer could come up with.

Michael Hancock
  • 2,260
  • 1
  • 17
  • 32
  • This is not official documentation and I am no security expert, but I wrote about this in more detail last year. Check it out if you like [here](https://michaelhancock.github.io/Hash-and-Salt/index.html). Hope it helps – Michael Hancock Oct 03 '17 at 07:21