Since this topic has come up more than once on Security SE, this answer is heavily based upon the answers there.
#The wrong way The number one rule of secure cryptograpy has to be: don't roll your own crypto[1]
As cryptography expert Bruce Schneider put it:
Anyone, from the most clueless amateur to the best cryptographer, can create an algorithm that he himself can't break. It's not even hard. What is hard is creating an algorithm that no one else can break, even after years of analysis. And the only way to prove that is to subject the algorithm to years of analysis by the best cryptographers around.[2]
A lot of reasons as to why you shouldn't try building your own cryptosystem can be found in this thread: Is my developer's home-brew password security right or wrong, and why? #The right way Use a hashing function – which, in contrast with the encryption/decryption code you posted, is one-way – that has been developed by experts and has been in widespread public use for yeas without having any security security issues found with it.
Read How to securely hash passwords? to understand what qualifies as a good password hashing scheme.
##The code
Fortunelately, PHP makes it easy for us to hash passwords the right way. Using the functions password_hash()
and password_verify()
, which by default use the bcrypt algorithm with a proper salt and sufficient cost*.
These functions have been in PHP since version 5.5; however, a compatibility library is available for PHP version 5.3.7 and greater.
* cost means how hard it is to calculate a password hash for you and for any attacker that obtains the password hashes. If the cost of hashing is too low, it becomes easy for an attacker to obtain the password matching a hash by trying possible solutions (brute-forcing). If it is too high, hashing will be too slow for your users and your server may not be able to cope with the load.
- 233
- 1
- 5