PHP password Encryption

I was wondering how to encrypt passwords better with PHP. Up til now, I used MD5 and SHA1 but both now have online decryptors that work fast. Is there a better function?

The way those decrypters work is by amassing a large database of strings along with the hash value of those strings. So they’re not “decrypting” in the traditional sense, but rather just looking up the hash in a dictionary of precomputed hashes. Every hash algorithm is vulnerable to this kind of exploit, so no matter which algorithm you use, it’s standard practice to add random data to the string before you hash it. We call that technique “salting the hash.” The databases of precomputed hashes can’t actually store every possible hash – there are more than 10^38 of them – so instead they store only the hashes of common passwords. By adding random data to each password before we hash it, we ensure that the hash we get back won’t be in one of those databases.

However, even though neither MD5 nor SHA1 are specially vulnerable to this trick, that doesn’t mean you shouldn’t still use a better algorithm. The most popular choice at the moment is SHA-256.

There are other standard tricks we can do, such as hashing the string repeatedly, perhaps 1000 times, in order to make it take longer to compute the hash. That makes it harder for an attacker to guess the password, because every guess would take 1000x more compute time.

Doing all this correctly may be more hassle than you want to deal with, so you may want to let a library do the work for you. I’ve seen many smart people here recommend phpass, and it’s certainly worth checking out. Although, personally, I’m underwhelmed by the code quality in that library.

Otherwise, you could do this:

$salt = uniqid(mt_rand(), true);
$hashedPassword = hash_pbkdf2('sha256', $password, $salt, 1000);

You’ll need to store both the hash and the salt in your database.