使用php无法使用字符串比较

时间:2014-05-18 23:44:12

标签: php encryption string-comparison blowfish crypt

所有以下行的来源:http://www.the-art-of-web.com/php/blowfish-crypt/

我使用此方法检查我的服务器是否接受河豚加密:

if(defined("CRYPT_BLOWFISH") && CRYPT_BLOWFISH) echo "CRYPT_BLOWFISH is enabled!<br>";

那没关系:

  

CRYPT_BLOWFISH已启用!

我用这种方法制作河豚盐

function getBlowFishSalt() { 
    $salt = ""; 
    $salt_chars = array_merge(range('A','Z'), range('a','z'), range(0,9)); 
    for($i=0; $i < 22; $i++) { 
        $salt .= $salt_chars[array_rand($salt_chars)]; 
    }

    return ($salt);
} 

那没关系。我使用以下

  

ZTbCMA3q8QY3A9a6E13JSn

我使用以下方法来加密密码:

function crypt_blowfish($input, $salt, $rounds = 12) { 
    return crypt($input, sprintf('$2a$%02d$', $rounds) . $salt); 
}

使用以下步骤:

$salt = "ZTbCMA3q8QY3A9a6E13JSn";

$password = "just_a_password";
print($password . " crypted as : <input type='text' size='80' value='" . crypt_blowfish($password, $salt) . "'><br>");

我得到以下哈希密码:

  

$ 2A $ 12 $ ZTbCMA3q8QY3A9a6E13JSe7pxGA6JsO.ksFGGeayxWXhcJalJ5ytm

然后我尝试比较一下:

$hashedPassword = "$2a$12$ZTbCMA3q8QY3A9a6E13JSe7pxGA6JsO.ksFGGeayxWXhcJalJ5ytm";

if (crypt_blowfish("just_a_password", $salt) == $hashedPassword)
    print ("just_a_password" . "recognized<br>");
else 
    print ("just_a_password" . " ---------- " . crypt_blowfish("just_a_password", $salt) . " ------------- " ." ko<br>");

if (crypt_blowfish("just_a_password", $salt) === $hashedPassword)
    print ("just_a_password" . "recognized<br>");
else 
    print ("just_a_password" . " ---------- " . crypt_blowfish("just_a_password", $salt) . " ------------- " ." ko<br>");

if (strcmp(crypt_blowfish("just_a_password", $salt), $hashedPassword) == 0)
    print ("just_a_password" . "recognized<br>");
else 
    print ("just_a_password" . " ---------- " . crypt_blowfish("just_a_password", $salt) . " ------------- " ." ko<br>");

但这些都没有给我带来好结果。 在屏幕上和HTML代码中,字符串完全相同,所以我不明白为什么php代码不能识别这些字符串。

你能帮助我吗?

1 个答案:

答案 0 :(得分:2)

奥利弗,

我想我找出了你的问题,当你使用双引号时,php将字符串解释为$作为变量。如果你改变了

$hashedPassword = "$2a$12$ZTbCMA3q8QY3A9a6E13JSe7pxGA6JsO.ksFGGeayxWXhcJalJ5ytm";
print($hashedPassword);

为:

$hashedPassword = '$2a$12$ZTbCMA3q8QY3A9a6E13JSe7pxGA6JsO.ksFGGeayxWXhcJalJ5ytm';
print($hashedPassword);

您的代码应该开始工作了。

您可以看到与print语句的区别。