比较两个加密的字符串

比较两个加密的字符串

本文介绍了PHP Crypt()比较两个加密的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以比较两个 crypt -ed字符串,看看它们是否匹配?

Is it possible to compare two crypt-ed strings and see if they match?

用户登录,创建一个会话,该会话存储用户的ID及其对应的crypt -ed密码哈希.在后台进行检查,以查看会话(读取,密码)是否仍然有效.

A user logs in, a session is created storing the user's ID and its corresponding crypt-ed password hash. In the background a check keeps running to see if the session (read, password) is still valid.

所以从技术上讲,我想将数据库中的crypt -ed密码与会话中的加密密码进行比较.这可能吗?

So technically I want to compare the crypt-ed password in the database with the crypted password in the session. Is this possible?

应该说我正在使用以下方法来加密密码;

Should've said I was using the following method to crypt a password;

    function better_crypt($input, $rounds = 7)
  {
    $salt = "";
    $salt_chars = array_merge(range('A','Z'), range('a','z'), range(0,9));
    for($i=0; $i < 22; $i++) {
      $salt .= $salt_chars[array_rand($salt_chars)];
    }
    return crypt($input, sprintf('$2a$%02d$', $rounds) . $salt);
  }

推荐答案

只需检查 crypt 上的PHP手册.该示例明确说明了如何验证密码(以及如何比较).

Just check the PHP Manual on crypt. The example clearly states how you can validate the password (so how to compare).

<?php
$hashed_password = crypt('mypassword'); // let the salt be automatically generated

/* You should pass the entire results of crypt() as the salt for comparing a
   password, to avoid problems when different hashing algorithms are used. (As
   it says above, standard DES-based password hashing uses a 2-character salt,
   but MD5-based hashing uses 12.) */
if (crypt($user_input, $hashed_password) == $hashed_password) {
   echo "Password verified!";
}
?>

您可以(当然)直接比较两个散列密码(因为它们都是字符串),但是不能保证它们相等.

You can (of course) compare two hashed passwords directly (as they are both strings), but they are just not guaranteed to be equal.

请注意,crypt可能不是非常"安全的.在> 保护PHP密码的哈希和盐值 ,然后查看有关密码哈希的PHP手册条目: http://php.net/faq.passwords-应该会让您入门.

Just be careful that crypt may not be "very" secure. Read more at Secure hash and salt for PHP passwords and see the PHP manual entry about password hashing: http://php.net/faq.passwords - that should get you started.

这篇关于PHP Crypt()比较两个加密的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 11:16