Я успешно создал свои пароли и вставляю их в базу данных с помощью CRYPT_BLOWFISH. Однако я не знаю, как сопоставить зашифрованные пароли в базе данных с паролями, которые пользователь вводит для входа. Любая помощь очень благодарна.
Чтобы сгенерировать пароль из ввода пользователя, я использую:
register.php
//If there are no errors or returned_records and the form is submitted let's submit the info and register the user else if(!$error_msg && !$returned_record && $_POST['register']){ //Place the newly hased/encrypted password into our new_password variable function generateHash($password_1){ if(defined("CRYPT_BLOWFISH") && CRYPT_BLOWFISH){ $salt = '$2y$11$'. substr(md5(uniqid(rand(), true)), 0, 22); return crypt($password_1, $salt); }//End If }//End Function genrateHash*/ $new_password = generateHash($password_1); $pass = $new_password; //Build our query $sql = ("INSERT INTO members (username, email, password_1) VALUES (?,?,?)"); //Prepare our query $stmt = $mysqli->prepare($sql) or die("Failed Execution"); //Bind the fields and there paramters to our query $stmt->bind_param('sss', $username, $email, $new_password); //Execute the query $stmt->execute(); echo $stmt->error; header('Location: http://www.yourschoolsincanada.com/english/register/registration-success/'); exit(); }
login.php
if(isset($_POST['login'])){ $username = $_POST['username']; $password_1 = $_POST['password_1']; $sql = "SELECT member_id, username, password_1 FROM members WHERE username = ? AND password_1 = ? LIMIT 1"; //Prepare our query if($stmt = $mysqli->prepare($sql)){ //Bind the Parameters to the query $stmt->bind_param('ss', $username, $password_1); //Execute the query $result = $stmt->execute(); /*Store our result to get properties*/ $stmt->store_result(); //Get the number of rows $num_of_rows = $stmt->num_rows; //Bind the results of what the query gave us to our three variables $stmt->bind_result($id, $username, $password_1); if(crypt($password_1, $pass) == $pass){ echo "Match"; } else{ echo "Passwords don't match"; } }
вif(isset($_POST['login'])){ $username = $_POST['username']; $password_1 = $_POST['password_1']; $sql = "SELECT member_id, username, password_1 FROM members WHERE username = ? AND password_1 = ? LIMIT 1"; //Prepare our query if($stmt = $mysqli->prepare($sql)){ //Bind the Parameters to the query $stmt->bind_param('ss', $username, $password_1); //Execute the query $result = $stmt->execute(); /*Store our result to get properties*/ $stmt->store_result(); //Get the number of rows $num_of_rows = $stmt->num_rows; //Bind the results of what the query gave us to our three variables $stmt->bind_result($id, $username, $password_1); if(crypt($password_1, $pass) == $pass){ echo "Match"; } else{ echo "Passwords don't match"; } }
У меня есть следующее, чтобы работать. Форма HTML и PHP все работают на одной странице.
<?php DEFINE ('DB_USER', 'xxx'); DEFINE ('DB_PASSWORD', 'xxx'); DEFINE ('DB_HOST', 'xxx'); DEFINE ('DB_NAME', 'xxx'); $mysqli = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die("could not connect"); if(isset($_POST['login'])){ $username = htmlentities(trim($_POST['username'])); $username = mysqli_real_escape_string($mysqli, $username); $password = trim($_POST['password']); $query = mysqli_query($mysqli, "SELECT username, password_1 FROM members WHERE username = '$username'"); $row = mysqli_fetch_assoc($query); $numrows = mysqli_num_rows($query); $dbuser = $row['username']; $dbpass = $row['password_1']; $hashed_password = crypt($password, $dbpass); // var_dump($dbuser); // For testing purposes only, can be removed echo "<hr>"; // var_dump($dbpass); // For testing purposes only, can be removed if( ($username == '') || ($password == '') ) { $error_string = '<font color=red>You have left either the username or password field blank!</font>'; echo $error_string; } if ($numrows == 0) { $error_string = '<font color=red>No username can be found!</font>'; echo $error_string; } else if ($numrows == 1) { if ($hashed_password == $dbpass) { $error_string = '<font color=red>Details checked out</font>'; echo $error_string; } } else { $error_string = '<font color=red>There was an error. Please contact an Admin</font>'; echo "SORRY Charlie!"; } } // brace for isset login ?> <form action="" method="post"> Username: <input type="text" name="username"> <br> Password: <input type="text" name="password"> <br> <input type="submit" name="login" value="Submit"> </form>
в<?php DEFINE ('DB_USER', 'xxx'); DEFINE ('DB_PASSWORD', 'xxx'); DEFINE ('DB_HOST', 'xxx'); DEFINE ('DB_NAME', 'xxx'); $mysqli = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die("could not connect"); if(isset($_POST['login'])){ $username = htmlentities(trim($_POST['username'])); $username = mysqli_real_escape_string($mysqli, $username); $password = trim($_POST['password']); $query = mysqli_query($mysqli, "SELECT username, password_1 FROM members WHERE username = '$username'"); $row = mysqli_fetch_assoc($query); $numrows = mysqli_num_rows($query); $dbuser = $row['username']; $dbpass = $row['password_1']; $hashed_password = crypt($password, $dbpass); // var_dump($dbuser); // For testing purposes only, can be removed echo "<hr>"; // var_dump($dbpass); // For testing purposes only, can be removed if( ($username == '') || ($password == '') ) { $error_string = '<font color=red>You have left either the username or password field blank!</font>'; echo $error_string; } if ($numrows == 0) { $error_string = '<font color=red>No username can be found!</font>'; echo $error_string; } else if ($numrows == 1) { if ($hashed_password == $dbpass) { $error_string = '<font color=red>Details checked out</font>'; echo $error_string; } } else { $error_string = '<font color=red>There was an error. Please contact an Admin</font>'; echo "SORRY Charlie!"; } } // brace for isset login ?> <form action="" method="post"> Username: <input type="text" name="username"> <br> Password: <input type="text" name="password"> <br> <input type="submit" name="login" value="Submit"> </form>
Следующее должно работать, так как я получил « соответствие », используя следующее внутри того же файла.
Читайте комментарии внутри кода.
<?php $password_1 = "1234567890"; // User-entered password function generateHash($password_1){ if(defined("CRYPT_BLOWFISH") && CRYPT_BLOWFISH){ $salt = '$2y$11$'. substr(md5(uniqid(rand(), true)), 0, 22); return crypt($password_1, $salt); } } // Remove the echo. For testing purposes only echo $new_password = generateHash($password_1); $pass = $new_password; echo "<br>"; echo $pass; echo "<hr>"; // Verify that the password matches and use in your login page // Syntax: if(crypt($password_entered, $password_hash) == $password_hash) if(crypt($password_1,$pass) == $pass) { // password is correct echo "Match."; } else { echo "No match."; }
Генератор паролей:
<?php $password_1 = "1234567890"; // User-entered generated password // or from a form // $password_1 = $_POST['password']; // User-entered generated password function generateHash($password_1){ if(defined("CRYPT_BLOWFISH") && CRYPT_BLOWFISH){ $salt = '$2y$11$'. substr(md5(uniqid(rand(), true)), 0, 22); return crypt($password_1, $salt); } } // here you can enter the password into DB // since we have a successful echo // Remove the echo. For testing purposes only echo $new_password = generateHash($password_1); $pass = $new_password; echo "<br>"; echo $pass; echo "<hr>";
Проверка входа:
$password_1 = $_POST['password']; // User-entered password // DB codes example: $query = mysqli_query($con, "SELECT password FROM users WHERE password='".$password_1."'"); // Verify that the password matches and use in your login page // Syntax: if(crypt($password_entered, $password_hash) == $password_hash) if(crypt($password_1,$pass) == $pass) { // password is correct echo "Match."; } else { echo "No match."; }