数据库通过以下方式加密密码:
encrypt('password', CONCAT('$', MD5(RAND()))));
我在 PHP 中选择此值,并且想将其与用户输入进行比较。那么我该如何在 PHP 中重新创建上面的内容呢?我不明白的是,如果加密密码依赖于随机数,那么如何在 php 中生成相同的字符串并将其与原始字符串进行比较?
最佳答案
看来MySql函数encrypt()
使用了Unix crypt()
函数。在这种情况下,您很可能创建不安全的 DES 哈希值,并且“盐”将作为结果哈希值的一部分存储。为了进行验证,您可以使用 PHP crypt()
函数,如下所示:
$isPasswordCorrect = crypt($password, $existingHashFromDb) === existingHashFromDb;
请注意,以这种形式存储密码非常不安全,因为这种哈希算法对于哈希密码来说太快了。相反,您应该使用像 BCrypt 这样的 key 派生函数,PHP 有它自己的函数 password_hash()为此:
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);
关于php - 比较加密密码mysql/php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22536482/