如何阻止bcryptsalt每次更改登录密码


how to stop bcrypt salt from changing everytime for login password

我从https://stackoverflow.com/a/6337021/2115954获取了用于定义bcrypt函数的代码。密码的注册工作正常,并将所有字段保存到数据库中的表中。问题是password_login不起作用,因为当它被散列时,加入了盐,它添加了不同的盐。这里的问题是什么,我该如何解决它。

我试过的事

  • 尝试从new bcrypt中去除new
  • 在登录脚本和注册脚本中添加$salthash('$password_login', $salt)
  • 寻找与我类似的情况,我所发现的都是关于比较散列$password_login和存储的问题/主题,散列$pswd在一起
  • 还添加了echo "$hash", echo "$isGood",以确定它们是否正在被验证,以及它们看起来像什么,而不去数据库寻找它们

index.php中的登录脚本

<?
//Login Script
if (isset($_POST["user_login"]) && isset($_POST["password_login"])) {
    $user_login = (!empty($_POST['user_login'])) ? $_POST['user_login'] : ''; // filter everything but numbers and letters
    $password_login = (!empty($_POST['password_login'])) ? $_POST['password_login'] : ''; // filter everything but numbers and letters 
        $bcrypt = new Bcrypt(10);
        $hash = $bcrypt->hash('$password_login', $salt);
        $isGood = $bcrypt->verify('$password_login', $hash);
        echo "$hash";
        exit();
    $db = new PDO('mysql:host=localhost;dbname=socialnetwork', 'root', 'abc123');
    $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
    $sql = $db->prepare("SELECT id FROM users WHERE username = :user_login AND password = :password_login LIMIT 1");
    if ($sql->execute(array(
    ':user_login' => $user_login,
    ':password_login' => $hash))) {
        if ($sql->rowCount() > 0){
            while($row = $sql->fetch()){
                $id = $row["id"];
            }
            $_SESSION["id"] = $id;
            $_SESSION["user_login"] = $user_login;
            $_SESSION["password_login"] = $hash;
        } else {
            echo 'Either the password or username you have entered is incorrect. Please check them and try again!';
            exit();
        }
    }
}
?>

在index.php中注册脚本

<?
class Bcrypt {
  private $rounds;
  public function __construct($rounds = 12) {
    if(CRYPT_BLOWFISH != 1) {
      throw new Exception("bcrypt not supported in this installation. See http://php.net/crypt");
    }
    $this->rounds = $rounds;
  }
  public function hash($input) {
    $hash = crypt($input, $this->getSalt());
    if(strlen($hash) > 13)
      return $hash;
    return false;
  }
  public function verify($input, $existingHash) {
    $hash = crypt($input, $existingHash);
    return $hash === $existingHash;
  }
  private function getSalt() {
    $salt = sprintf('$2a$%02d$', $this->rounds);
    $bytes = $this->getRandomBytes(16);
    $salt .= $this->encodeBytes($bytes);
    return $salt;
  }
  private $randomState;
  private function getRandomBytes($count) {
    $bytes = '';
    if(function_exists('openssl_random_pseudo_bytes') &&
        (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')) { // OpenSSL slow on Win
      $bytes = openssl_random_pseudo_bytes($count);
    }
    if($bytes === '' && is_readable('/dev/urandom') &&
       ($hRand = @fopen('/dev/urandom', 'rb')) !== FALSE) {
      $bytes = fread($hRand, $count);
      fclose($hRand);
    }
    if(strlen($bytes) < $count) {
      $bytes = '';
      if($this->randomState === null) {
        $this->randomState = microtime();
        if(function_exists('getmypid')) {
          $this->randomState .= getmypid();
        }
      }
      for($i = 0; $i < $count; $i += 16) {
        $this->randomState = md5(microtime() . $this->randomState);
        if (PHP_VERSION >= '5') {
          $bytes .= md5($this->randomState, true);
        } else {
          $bytes .= pack('H*', md5($this->randomState));
        }
      }
      $bytes = substr($bytes, 0, $count);
    }
    return $bytes;
  }
  private function encodeBytes($input) {
    // The following is code from the PHP Password Hashing Framework
    $itoa64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    $output = '';
    $i = 0;
    do {
      $c1 = ord($input[$i++]);
      $output .= $itoa64[$c1 >> 2];
      $c1 = ($c1 & 0x03) << 4;
      if ($i >= 16) {
        $output .= $itoa64[$c1];
        break;
      }
      $c2 = ord($input[$i++]);
      $c1 |= $c2 >> 4;
      $output .= $itoa64[$c1];
      $c1 = ($c2 & 0x0f) << 2;
      $c2 = ord($input[$i++]);
      $c1 |= $c2 >> 6;
      $output .= $itoa64[$c1];
      $output .= $itoa64[$c2 & 0x3f];
    } while (1);
    return $output;
  }
}
$reg = @$_POST['reg'];
//declaring variables to prevent errors
//registration form
$fn = (!empty($_POST['fname'])) ? $_POST['fname'] : '';
$ln = (!empty($_POST['lname'])) ? $_POST['lname'] : '';
$un = (!empty($_POST['username'])) ? $_POST['username'] : '';
$em = (!empty($_POST['email'])) ? $_POST['email'] : '';
$em2 = (!empty($_POST['email2'])) ? $_POST['email2'] : '';
$pswd = (!empty($_POST['password'])) ? $_POST['password'] : '';
$pswd2 = (!empty($_POST['password2'])) ? $_POST['password2'] : '';
$d = date("y-m-d"); // Year - Month - Day
if ($reg) {
    if ($em==$em2) {
        // Check if user already exists
        $statement = $db->prepare('SELECT username FROM users WHERE username = :username');
            if ($statement->execute(array(':username' => $un))) {
                if ($statement->rowCount() > 0){
                    //user exists
                    echo "Username already exists, please choose another user name.";
                    exit();
                }
            }
                    //check all of the fields have been filled in
                        if ($fn&&$ln&&$un&&$em&&$em2&&$pswd&&$pswd2) {
                            //check that passwords match
                                if ($pswd==$pswd2) {
                                    //check the maximum length of username/first name/last name does not exceed 25 characters
                                        if (strlen($un)>25||strlen($fn)>25||strlen($ln)>25) {
                                            echo "The maximum limit for username/first name/last name is 25 characters!";
                                        }
                                        else
                                            {
                                                //check the length of the password is between 5 and 30 characters long
                                                    if (strlen($pswd)>30||strlen($pswd)<5) {
                                                        echo "Your password must be between 5 and 30 characters long!";
                                                    }
                                                    else
                                                        {
                                                            //encrypt password and password 2 using md5 before sending to database
                                                                $bcrypt = new Bcrypt(10);
$hash = $bcrypt->hash('$pswd', $salt);
echo "<p>$hash</p>";
$isGood = $bcrypt->verify('$pswd', $hash);
echo "<p>$isGood</p>";
                                                                $bcrypt2 = new Bcrypt(10);
$hash2 = $bcrypt2->hash('$pswd2', $salt);
echo "<p>$hash2</p>";
$isGood2 = $bcrypt2->verify('$pswd2', $hash2);
echo "<p>$isGood2</p>";
exit();                                                             
                                                                $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
                                                                $sql = 'INSERT INTO users (username, first_name, last_name, email, password, sign_up_date)';
                                                                $sql .= 'VALUES (:username, :first_name, :last_name, :email, :password, :sign_up_date)';
                                                                $query=$db->prepare($sql);
                                                                $query->bindParam(':username', $un, PDO::PARAM_STR);
                                                                $query->bindParam(':first_name', $fn, PDO::PARAM_STR);
                                                                $query->bindParam(':last_name', $ln, PDO::PARAM_STR);
                                                                $query->bindParam(':email', $em, PDO::PARAM_STR);
                                                                $query->bindParam(':password', $hash, PDO::PARAM_STR);
                                                                $query->bindParam(':sign_up_date', $d, PDO::PARAM_STR);
                                                                $query->execute();
                                                                die("<h2>Welcome to Rebel Connect</h2>Login to your account to get started.");
                                                        }
                                            }
                                }
                                else {
                                    echo "Your passwords do not match!";
                                }
                        }
                else
                    {
                        echo "Please fill in all fields!";
                    }
            }
    else {
        echo "Your e-mails don't match!";
    }
}
?>

更新的登录脚本

<?
//Login Script
if (isset($_POST["user_login"]) && isset($_POST["password_login"])) {
    $user_login = (!empty($_POST['user_login'])) ? $_POST['user_login'] : ''; // filter everything but numbers and letters
    $password_login = (!empty($_POST['password_login'])) ? $_POST['password_login'] : ''; // filter everything but numbers and letters 
    $db = new PDO('mysql:host=localhost;dbname=socialnetwork', 'root', 'abc123');
    $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
    $sql = $db->prepare("SELECT id, password FROM users WHERE username = :user_login LIMIT 1");
    $dbhash = $db->prepare("SELECT password FROM users WHERE username = :user_login LIMIT 1");
    $isGood = $bcrypt->verify('$_POST["password_login"]', $dbhash);
    echo "$isGood";
    exit(); //here for debugging purposes
    if ($sql->execute(array(
    ':user_login' => $user_login,
    ':password_login' => $hash))) {
        if ($sql->rowCount() > 0){
            while($row = $sql->fetch()){
                $id = $row["id"];
            }
            $_SESSION["id"] = $id;
            $_SESSION["user_login"] = $user_login;
            $_SESSION["password_login"] = $hash;
        } else {
            echo 'Either the password or username you have entered is incorrect. Please check them and try again!';
            exit();
        }
    }
}
?>

更新:我多少知道该把代码放在哪里了。我现在遇到的问题是,它没有重定向到主页,但我认为这是由于没有页面刷新造成的。最初,我让它在会话开始和用户登录时自动刷新。当我回到家时,我将再次更新代码以显示所做的更改。重载页面,它会转到home。php

错误:

$hash = $bcrypt->hash('$password_login', $salt);
$isGood = $bcrypt->verify('$password_login', $hash);

不要向verify()提供新的哈希值,而要提供从数据库中检索到的现有哈希值。

eg: $b->verify('password', '$2a$12$9bAvuaBrMlWmw8oI9flz9e6pjJniKVpRyr9Fz0ScQVwMJA53R3uQO');

同样,hash()函数只接受一个参数并生成自己的随机盐。

您的登录脚本的流程应该是:

  1. 用户提供用户名/密码
  2. SELECT id, password FROM users WHERE username = ?
  3. $isGood = $bcrypt->verify($password_login, $hash_from_db);
  4. ? ?
  5. 利润!

编辑

verify()/crypt()在后台看什么,也就是什么在存储的哈希中意味着什么

注意:在base64编码中,每个字符代表6位,

$ 2a $ 12 $ 9bAvuaBrMl W mw8oI9flz9e6pjJniKVpRyr9Fz0ScQVwMJA53R3uQO
  |    |    |          | |
  |    |    |          | > the rest of the salted, hashed password
  |    |    |          > this character is split, the first 4 bits are part
  |    |    |            of the salt, the last 2 are part of the hash
  |    |    > the salt
  |    > the number of hashing 'rounds' are performed
  > Scheme ID, 2a is blowfish