如何在登录时匹配用户名和加密密码 [英] How to match username with encrypted password on login

查看:167
本文介绍了如何在登录时匹配用户名和加密密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想加密一些密码并将其放入数据库。如何将这些东西保存在数据库中,如果所有者匹配,我可以检索数据。

I would like to encrypt some passwords and put it in database. How do I keep this stuff in a database so I can retrieve the data if the owner matches.

示例

<?php
// some validations and other staff
$data = $_POST['input'];
$hash = crypt($data);
//then database insert code
?>

如果我 echo $ hash ,它给我一些加密数据,但是当我刷新页面时,数字会不时变化。如何保持数据静态?输入用户名和密码时,如何告知加密的密码,这是所有者。

If I echo the $hash, it's giving me some encrypted data but when I refresh the page, the numbers are changing from time to time. How do I keep the data static? How will I tell the encrypted password that this was the owner when username and password entered.

示例

<?php
//time of encryption 
$name = "someone";
$pass = "p1x6Fui0p>j";
$hash = "$pass"; //outcome of $hash e.g. $1$aD2.bo0.$S93XNfgOFLskhis0qjE.Q/

// $hash and $name inserted in database
?>

当用户尝试使用收集详细信息登录时,我如何引用 $哈希$ 1 $ aD2.bo0。$ S93XNfgOFLskhis0qjE.Q /等于 $ pass p1x6Fui0p> j?

When the user tries to login with collect details, how will I refer $hash "$1$aD2.bo0.$S93XNfgOFLskhis0qjE.Q/" was equal to $pass "p1x6Fui0p>j" ?

推荐答案

crypt()有一个不幸的名字。这不是一个加密功能,而是单向散列函数。

crypt() has an unfortunate name. It's not an encryption function, but a one-way hashing function.

如果您使用PHP 5.5+,只需使用 password_hash password_verify

If you're using PHP 5.5+, just use password_hash and password_verify:

$hash = password_hash($data, PASSWORD_BCRYPT);  // Bcrypt is slow, which is good

并验证输入的密码:

if (password_verify($pass, $hash)) {
    // The password is correct
}

现在回答您的实际问题:密码散列的目的是在不实际存储其明文密码的情况下验证用户。如果 hash(a)== hash(b),那么你可以确定 a == b 。在你的情况下,你已经有 hash(a) $ hash ),所以你只需要哈希输入密码并比较生成的哈希值。

Now to answer your actual question: the purpose of password hashing is to authenticate users without actually storing their plaintext passwords. If hash(a) == hash(b), then you can be pretty sure that a == b. In your case, you already have hash(a) ($hash), so you just need to hash the inputted password and compare the resulting hashes.

crypt() b

if (crypt($pass, $hash) === $hash) {
    // The password is correct
}

这篇关于如何在登录时匹配用户名和加密密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆