2

一直试图在论坛和堆栈的问题中找到解决方案,但没有结果,所以你是我最后的希望。我使用 phpass 进行密码加密,注册脚本工作得很好,但是当我尝试登录并使用 CheckPassword 函数时,它总是返回 false。我正在添加我的两个 php 脚本:

报名:

 <?php 
 require 'phpass-0.3/PasswordHash.php';
 require 'config.php';

 $email = $_POST['email'];
 $confirmed_email = $_POST['confirmed_email'];
 $username = $_POST['username'];
 $password = $_POST['password'];



 if ($_SERVER['REQUEST_METHOD'] === "POST") {

 if(!preg_match("^[a-z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+(\.[a-z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,})$^", $email))
 {
    $errors[] = "Incorrect email format.";
 }

 if (($email)!==($confirmed_email))
 {
    $errors[] = "Emails do not match";
 }


 if ((strlen($username) < 5) || (!ctype_alnum($username)))
 {
    $errors[] = "Username must be min 6 signs and only include 0-9, A-Z characters.";
 }

 if ((strlen($password) < 7) || (!ctype_alnum($password)))
 {
    $errors[] = "Password must be min 8 signs and only include 0-9, A-Z characters.";
 }

 $stmt = $db->prepare('SELECT * FROM users WHERE username = ? LIMIT 1');
 $stmt->bind_param('s', $username);
 $stmt->execute();
 $stmt->store_result();

 if($stmt->num_rows == 1)
 {
    $errors[] = "Username is taken.";
 }


 else if (!count($errors)) {
 $hasher = new PasswordHash(8, false);
 $hash = $hasher->HashPassword($password);
 if (strlen($hash) >= 20) {
 $stmt = $db->prepare('insert into users (username, email, password) values (?, ?, ?)');
 $stmt->bind_param('sss', $username, $email, $hash);
 $stmt->execute();
 $stmt->close();
 $db->close();
     }
 }

   Foreach($errors as $v) print "$v <br/>";
 }

 ?>

登录:

<?php
include 'config.php';
require 'phpass-0.3/PasswordHash.php';

if(isset($_POST['email'], $_POST['password'])) { 
$email = $_POST['email'];
$password = $_POST['password'];




 $stmt = $db->prepare("SELECT id, username, password FROM users WHERE email = ? LIMIT 1");
 $stmt->bind_param('s', $email); 
 $stmt->execute();
 $stmt->store_result();
 $stmt->bind_result($user_id, $username, $hash);
 $stmt->fetch();

 $stored_hash = $hash;
 $hasher = new PasswordHash(8, false);


 $check = $hasher->CheckPassword($password, $stored_hash);

 if ($check) {

 echo"Logged IN"; 

 } else {

 echo "SOMETHING'S WRONG";
   }
 }
 ?>

请不要注意安全问题,因为它只是一个演示脚本,我还在学习中。

4

1 回答 1

0

确保散列密码为 60 个字符,否则将返回 false。我有同样的问题,注意到我的第一个散列密码是 61 个字符。

于 2013-11-07T10:46:24.320 回答