password_hash equivalent for php 5.4? [duplicate]

2020-02-10 23:00发布

问题:

I developed my site using XAMPP with php 5.5 installed. I just realize that my host only has php 5.4 (cannot update to 5.5 yet). My problem is that I cannot use the new php 5.5 password_hash() feature. Is there an equivalent method for hashing with salt for php 5.4?

Is there a way to get this equivalent code (below) to work in php 5.4?

$options = [
  'salt' => uniqid(mt_rand(), true),
  'cost' => 12 
];
$hash = password_hash($mypassword, PASSWORD_DEFAULT, $options);

回答1:

Use password_compat. It's a backward compatible library to emulate password_hash() in older versions of PHP (5.3.7+).



回答2:

When I was using PHP 5.4 I used php's crypt function with CRYPT_BLOWFISH hash type. I played a bit with parameters to match your case, and concluded that your blowfish Pre should be $2y$12$ to match your cost = 12 parameter.

You can run this script in your command line to verify the result matches (I will keep your insecure mt_rand salt in this part. More on this later)

<?php

$salt= uniqid(mt_rand(), true);
$options=['salt'=>$salt, 'cost'=>12];
$mypassword=$argv[1];

$cryptpwd=crypt($mypassword,'$2y$12$'.$salt.'$'); // PHP 5.4 style

$pwdhash=password_hash($mypassword, PASSWORD_DEFAULT, $options);  // PHP 5.5+

echo "\n";
echo 'CRYPT    :'. $cryptpwd;
echo "\n";
echo 'PWD HASH :'. $pwdhash;
echo "\n";

if($cryptpwd===$pwdhash) {
    echo 'Hashes match!';
} else {
    echo 'Hashes do not match';
}
echo "\n";

For example

php pwd.php 1q2w3e4r5t

outputs

CRYPT    :$2y$12$22253563353f27f9b3292ereZv98r1iFQhItfYT0UbKaejMSJThBi
PWD HASH :$2y$12$22253563353f27f9b3292ereZv98r1iFQhItfYT0UbKaejMSJThBi
Hashes match!

@JohnConde's answer is better because is safer using a well tested library. I just wanted to see what was going below the trunk.

PD: You asked

Is there a way to get this equivalent code (below) to work in php 5.4?

Now, your code has a major weakness. You are generating salts with mt_rand. Don't ever do that. Trust the system with the salt generation and, if you really want to generate it yourself, use something like the following salt generator (I used thisone when my apps were PHP 5.4)

$Allowed_Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789./';
$Chars_Len = 63;
$Salt_Length = 21;
$salt = "";
$Blowfish_Pre='$2y$12$';
$Blowfish_End='$';

for ($i = 0; $i < $Salt_Length; $i++) {
    $salt.= $Allowed_Chars[mt_rand(0, $Chars_Len) ];
}

$bcrypt_salt = $Blowfish_Pre . $salt . $Blowfish_End;

To be honest I was sure the salt had 18 characters, but looking at my old code, it's done with 21 :)