字符串比较不工作使用php


String comparison not working using php

以下所有行的来源: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);
} 

这没关系。I使用以下

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

我得到以下散列密码:

2美元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>");

但是这些都没有返回一个OK的结果。在屏幕上和进入HTML代码,字符串是完全相同的,所以我不明白为什么php代码不识别这些是相同的。

你能帮我吗?

Oliver,

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

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

:

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

你的代码应该开始工作。

您可以看到print语句的区别