Compare or view hashed passwords in PHP

429 Views Asked by At

I have the following PHP script to hash a user's password which it does, HOWEVER, when I try to compare the hashed variable to the original password, it returns false.

$hash=hash("whirlpool","hello");

if("hello"===$hash){echo "TRUE";}
else{echo "FALSE";}

Does anyone know what I am doing wrong or what can I do to improve this code to actually work properly? I need the hash to be the same as the variable so I can actually use this.

SIDE NOTE: I want to use a good sized encryption (which is why I'm using the "whirlpool" algorithm) so I would prefer not to use md5, sha1, etc...

Thanks in advance.

3

There are 3 best solutions below

2
On BEST ANSWER

Shouldn't you compare the values as

if(hash('whirlpool', 'hello') === $hash) echo 'true';
else echo 'false';
2
On

when comparing the hash, you probably want to hash the compared value as well, e.g.

$hashed_password = hash("whirlpool", "hello");
$input = "hello";

if (hash("whirlpool", $input) === $hashed_password) {
    echo "TRUE";
} else {
    echo "FALSE";
}

P.S.: If you really want to use whirlpool, append a salt. Also, follow the best practices found on OWASP.

0
On

A hash-function is a one-way cryptographic algorithm (one-way means that you can't calculate the input from a given output). It takes an input and spits out a pretty long number (often represented in hex format). So when you apply a hash algorithm on a given input (in your case you apply the whirlpool algorithm on "hello") it returns a digest (in your case digest hex string would be 0a25f55d7308eca6b9567a7ed3bd1b46327f0f1ffdc804dd8bb5af40e88d78b88df0d002a89e2fdbd5876c523f1b67bc44e9f87047598e7548298ea1c81cfd73). Obviously "hello" does not equals "0a25f..". A common scenario for using hash algorithms is to secure passwords persisted in a database or some other kind of identity storage. So when comparing a given password (e.g. submitted by a user) you have to calculate the hash of this given password and compare it to the stored hash.

So instead of comparing "hello" to the previously generated hash, you would like to compare the hash of "hello" to the previously generated hash.

$hash = hash("whirlpool","hello");
if(hash("whirlpool","hello") === $hash){
    echo "true";
}

Assuming that you want to check a submitted password, you could write something like this:

$pw_stored = "0a25f..." //(... left out some chars) that's the hash you got from the db
if(hash('whirpool', $_POST['password']) === $pw_stored){ // $_POST['password'] is the password a user has entered in a login form 
    echo "true";
}