Search code examples
hashasp.net-identitysha256shasalt-cryptography

How is a password checked against a hashed and salted password?


If a user creates a new password and this goes through a hash algorithm and is stored in the database, it can then be matched up with the user's entered password when they log in. The password entered into the login screen is hashed and then checked to see if it matches the stored hash. If it does, it allows the user access.

However, nowadays, passwords are hashed and salted. So when the user first registers their password, it goes through a hash, and then it gets salted over 10,000 times. Is this salt with the same keyword generated by the backend code, or is it randomly generated for each time it gets salted?

When the user enters the password to log in, how does it match up to the hash and salted password, if the salt is random each time, surely it will end up with a different hash? That's why even if two users entered the same password, they end up with a different hashes.


Solution

  • Great questions!

    So when the user first registers their password, it goes through a hash, and then it gets salted over 10,000 times. Is this salt with the same keyword generated by the backend code, or is it randomly generated for each time it gets salted?

    The actual mechanics of how salting and hashing words vary from implementation to implementation. However, the general idea behind a salt is to generate, for each stored password, a random piece of information called the salt. The stored value is then derived from a hash of the password itself mixed with the salt in some way. It could be that you hash the password and then run lots of rounds of combining the hash with the salt, or perhaps you just concatenate the password and salt together and hash it lots of times.

    It's essential, for this process to work, that you have a different salt for each password. If you use the same salt each time, then every copy of the same password will look the same after you're done hashing it and combining it with the salt. This leaks information, which is not a good thing.

    When the user enters the password to log in, how does it match up to the hash and salted password, if the salt is random each time, surely it will end up with a different hash?

    When the server checks the password, it needs to have access to the salt that it used when storing the password. Otherwise, it has no way of recalculating the stored value from the password. The salts are usually stored right next to the final hash. The idea is that the salt isn't the secret - the password is - and so it's fine to just store it alongside.

    That's why even if two users entered the same password, they end up with a different hashes.

    Yep, each password is stored with a different salt. Each salt is randomly generated, but then stored alongside the final password hash.