编程语言
首页 > 编程语言> > 为什么PHP crypt()函数为两个不同的字符串返回相同的东西?

为什么PHP crypt()函数为两个不同的字符串返回相同的东西?

作者:互联网

我正在使用PHP的crypt函数进行密码散列/加密,但我不认为我做得对,因为“nathan12”和“nathan123”都允许我在我的系统上登录我的帐户(实际密码是“nathan123” “,因此”nathan12“或其他任何东西都不允许我登录).

这是我的系统在用户注册时所执行的操作:

[...]

$salt = uniqid(mt_rand(), true);
$password = crypt($password, $salt); // '$password' is the inputted password

$insertUserStmt = $mysqli->prepare("INSERT INTO users (name, 
username, 
password, 
password_salt, 
email, 
created) VALUES (?, ?, ?, ?, ?, ?)");

$insertUserStmt->bind_param("sssssi", $name, $username, $password, $salt, $email, time());

$insertUserStmt->execute();

[...]

它将散列/加密密码($password)与$salt一起插入数据库.

当有人尝试登录时,会执行以下操作来检查用户是否输入了他们输入的用户名的正确密码:

[...]

// $password_salt is from DB; $password is inputted password
$password_crypt = crypt($password, $password_salt); 

// $login_password is from DB
if($password_crypt == $login_password) { 

[...]

我可能甚至没有正确使用crypt函数,但根据PHP文档,第一个参数是字符串(密码),第二个是salt.

解决方法:

The standard DES-based crypt() […] only uses the first eight characters of str, so longer strings that start with the same eight characters will generate the same result (when the same salt is used).

source

使用以$< algo> $开头的盐来使用除DES之外的其他内容.有关详细信息,请参阅crypt()文档.

标签:php,mysql,password-protection
来源: https://codeday.me/bug/20191002/1843918.html