Security Alert: Do NOT Decrypt Passwords
Many applications require a user to log in. A friend was trying to implement his version, and was concerned how to decrypt the password stored in the database. Below was my advice.
Take the password that the user entered and concatenate it with a standard string (unique to your app; make it up!).
This is called “salting a hash”
Then take that new string and encrypt it. Awhile ago I used PHP’s built-in function md5(), although visiting the site now it clearly says to not use it for this purpose!
Store the new encrypted value in your database. This value should NOT be decrypted.
When the user logs in to your app, you’ll get the password that they typed in. Again, concatenate it with the same unique string for your app, and encrypt it using the same algorithm as before.
Now compare if the two strings match. If they do, then the user should be authenticated. (With PHP, this is where you would set a session variable). At no point should you decrypt the password from the database to see if it matches.
It’s not a matter of “encrypt and decrypt the password.” Instead, it’s “do the two encrypted values match?”
Edit: from the comments, I should have been using the word “hash” above instead of “encrypt.” Thanks everyone!