# Encrypting and decrypting passwords in PHP

I am wanting to encrypt a password and decrypt a password using PHP. Is this a safe method?

$pass = "password" //encrypt password$salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');
$salt = sprintf("$2a$%02d$", 10) . $salt;$hash = crypt($pass,$salt);

//decryption in second program
if(crypt($pass,$hash) == \$hash){
echo "you are in";
}

• You should NEVER encrypt passwords. Hash them. – evandentremont Mar 27 '15 at 16:05
• 1. Don't use a fast hash; it's important to use a slow hash function. 2. security.stackexchange.com/q/211/971 covers the considerations pretty well. – D.W. Mar 27 '15 at 18:03

As KIKO Software and the documentation for crypt said, password_hash() is encouraged. It's safer (it applies multiple rounds of hashing, thus increasing the time it takes to decrypt the hash), and it will manage salts for you, which means that your code will be simpler.

If for some reason you do not want to use password_hash, note the warning from the crypt documentation:

Warning When validating passwords, a string comparison function that isn't vulnerable to timing attacks should be used

You are not doing that, you are just using ==. hash_equals would be one such timing safe function.

• Good point about timing attacks. – KIKO Software Mar 27 '15 at 12:32

The name of the function crypt() is somewhat misleading, but you're not encrypting and decrypting. You create a hash and you check it, that's it.

It's not the best I have seen, but it is not uncommon to do it this way.

In the PHP crypt() documentation it says: Use of password_hash() is encouraged. You didn't see that? It allows you to choose an algorihtm. The PASSWORD_BCRYPT algorithm should be used. See: http://codahale.com/how-to-safely-store-a-password

I also see that you're not really using a salt in the traditional manner. Here's a nice introduction: http://www.martinstoeckli.ch/hash/en/index.php

So you're not using a salt on a per-password basis. See: http://blog.codinghorror.com/youre-probably-storing-passwords-incorrectly