密码哈希使用各种方法

时间:2012-10-18 21:30:27

标签: php security hash login passwords

我一直在寻找存储用户密码的最佳方式,但我并没有真正考虑安全性,所以我发现了大量有关加密的信息以及使用Google的相关信息。

我不喜欢使用我可以在互联网上的博客或网站上获得的片段,我宁愿创建自己的解决方案,所以我最终开发了两个函数:一个用于创建哈希,另一个用于检查“哈希”密码。

我不知道我做得对,或者我只是在增加我的问题,所以看看下面的功能。

// Creates a simple password's hash
function hashPassword( $password = false )
{
  // Checks if the password has more than 6 characters
  if( strlen( $password ) < 6 )
  {
    // Kills the script
    exit('Password is too short.');
   }

   // Split the 4 first characters of the password
   $salt = substr( $password, 0, 4 );

   // Calculate the md5 hash of the salt
   $salt = md5( $salt );

   // Get the rest of the password
   $password =  substr( $password, 3, strlen( $password ) );

   // Calculate the md5 hash of the password
   $password = sha1( $salt . $password );

   // Crypt the password
   $password = crypt( $password );

   return $password;
}

这是我要存储的密码。现在,看看我要检查密码是否正确的方式。

// Checks if a hashed password match a user input password
function checkHashedPassword( $password = false, $hashedPassword = false )
{
// Checks if the password has more than 6 characters
if( strlen( $password ) < 6 )
{
    // Kills the script
    exit('Password is too short.');
}

// Split the 4 first characters of the password
$salt = substr( $password, 0, 4 );

// Calculate the md5 hash of the salt
$salt = md5( $salt );

// Get the rest of the password
$password =  substr( $password, 3, strlen( $password ) );

// Calculate the md5 hash of the password
$password = sha1( $salt . $password );

// Checks the password and hash
if( crypt( $password, $hashedPassword ) == $hashedPassword ) 
{
    // Returns true
    return true;
}

// Returns false by default
return false;
}

正如您所注意到的,我将创建一个存储密码的变量,我可以检查它是否正常,如下面的代码:

$pass = hashPassword( $_POST['password'] );

if( !checkHashedPassword( $_POST['password'], $pass ) ) 
{
    exit('Password incorrect!');
}

那么,它会安全地运作吗?

3 个答案:

答案 0 :(得分:3)

如果您正在寻找一种通用且简单的方法,Adding simple password hashing API仍然在RFC for php中,但有非常好的implementation by ircmaxwell,您可以使用

示例

  $hash = password_hash($password, PASSWORD_BCRYPT);

验证

if (password_verify($password, $hash)) {
    /* Valid */
} else {
    /* Invalid */
}

Download Here

答案 1 :(得分:1)

您可以使用:

$pass = <query password code>;

if( $pass != hashPassword( $_POST['password'] ); ) 
{
    exit('Password incorrect!');
}

答案 2 :(得分:1)

OWASP的Password Storage Cheat Sheet为密码存储和散列提供了很好的指导。

关键点是使用强盐,并迭代哈希值(当前64,000次或更多)。

一个好的,广泛使用的用于密码哈希的PHP库是OpenWall的Portable PHP Password Hashing Framework,我建议检查一下。

相关问题