HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Encrypting and decrypting passwords in PHP

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
phppasswordsencryptingdecryptingand

Problem

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";
}

Solution

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

There's much to say about this topic. Password security is a hot topic.

One of the mistakes most programmers make is that they rely on the user to select a password. In general users are just plain bad at choosing a secure password. You can try and force them to choose one, which is probably secure, but by doing that you will only annoy the hell out of the user. The solution is quite simple: You choose the password for the user. For a site where security is not that paramount you can use simple password. A random five digit number, in combination with a email address and brute force protection, is already reasonable secure; there are a million different possible combinations. Most developers however stick to what they know.

Context

StackExchange Code Review Q#85149, answer score: 6

Revisions (0)

No revisions yet.