password_hash密码哈希与安全

支持PHP5.5+
项目中大部分加密基于MD5+SALT,事实上password_hash()已经帮我们处理好了加盐。加进去的随机子串通过加密算法自动保存着,成为哈希的一部分。password_verify()会把随机子串从中提取,所以你不必使用另一个数据库来记录这些随机子串,大大简化了计算密码哈希值和验证密码的操作。

string password_hash ( string $password , integer $algo [, array $options ])
boolean password_verify ( string $password , string $hash )

此外还包含两个函数:
password_get_info() //查看哈希值的相关信息
password_needs_rehash() //检查一个hash值是否是使用特定算法及选项创建的

当过去一段时间后,我们想将用户加密的哈希密码增强升级,可以使用password_needs_rehash()来检查用户密码哈希值是否需要更新,比如将工作因子从10升到20,重新计算密码哈希值,让密码变得更安全。

<?php
$password = 'rasmuslerdorf';
$hash = '$2y$10$YCFsG6elYca568hBi2pZ0.3LDL5wjgxct1N8w/oLR/jfHsiQwCqTS';

// The cost parameter can change over time as hardware improves
$options = array('cost' => 11);

// Verify stored hash against plain-text password
if (password_verify($password, $hash)) {
    // Check if a newer hashing algorithm is available
    // or the cost has changed
    if (password_needs_rehash($hash, PASSWORD_DEFAULT, $options)) {
        // If so, create a new hash, and replace the old one
        $newHash = password_hash($password, PASSWORD_DEFAULT, $options);
    }

    // Log user in
}

优缺点:虽然通过password_hash()创建的哈希密码更加安全,但使用password_hash()加密的哈希值基本只能通过PHP的password_verify来校验。

Tags: PHP

添加新评论