每个单词的哈希输出都是相同的

时间:2014-05-27 18:00:52

标签: php mysql hash mysqli sha256

我试图在PHP中哈希插入的密码但是无论插入什么密码,SHA输出总是相同的。 这是我的文件, 创建-user.php的:

<?php include 'header.php' ?>
<body>
  <form action="insert-user.php" method="post" role="form">
    <div class="form-group">
      <label for="username">Enter Username:</label>
      <input type="text" class="form-control" name="username" placeholder="e.g. username12" required>
    </div>
    <div class="form-group">
      <label for="password">Enter Password:</label>
      <input type="password" class="form-control" name="password" placeholder="e.g. mypass912" required>
    </div>
    <div class="form-group">
      <label for="email">Enter Email Address:</label>
      <input type="email" class="form-control" name="email" placeholder="e.g. myemail56@hotmail.com" required>
    </div>
    <div class="form-group">
      <label for="bdate">Your Birthdate:</label>
      <input type="date" class="form-control" name="bdate" required>
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
  </form>
</body>
</html>

这里是insert-user.php:

<?php
include 'header.php';
$username=mysqli_real_escape_string($con,$_POST['username']);
$password=mysqli_real_escape_string($con,hash('sha256','$_POST[password]'));
$email=mysqli_real_escape_string($con,$_POST['email']);
$bdate=mysqli_real_escape_string($con,$_POST['bdate']);

$sql="INSERT INTO users (username,password,email,bdate)
    VALUES('$username','$password','$email','$bdate')";
if (!mysqli_query($con,$sql)) {
  die('Error: ' . mysqli_error($con));
}
    echo "User added!";

mysqli_close($con);
?>

有人可以解释我如何让SHA2功能正常工作吗?

3 个答案:

答案 0 :(得分:2)

此版本使用bind_param和正确的密码编码机制:

<?php
include 'header.php';

$sql = "INSERT INTO users (username,password,email,bdate) VALUES(?,?,?,?)";

$stmt = mysqli_prepare($con, $sql);

mysqli_stmt_bind_param('ssss',
  $_POST['username'],
  password_hash($_POST['password'), PASSWORD_DEFAULT),
  $_POST['email'],
  $_POST['bdate']
);

if (!mysqli_stmt_execute($con,$stmt)) {
  die('Error: ' . mysqli_error($con));
}
    echo "User added!";

mysqli_close($con);
?>

当你不必担心它时,更容易获得引用。

答案 1 :(得分:1)

'$_POST[password]'左右删除引号。当变量放在单引号内时,变量不会被转换为它的值。它是文字字符串。在您的代码中,您每次只是散列字符串$_POST[password],而不是变量。

答案 2 :(得分:1)

变化

$password=mysqli_real_escape_string($con,hash('sha256','$_POST[password]'));

$password=mysqli_real_escape_string($con,hash('sha256', $_POST['password']));