2011-10-06 106 views
0

现在我正在开发一个允许在线注册的应用程序。对于开发,密码检查只检查一个MySQL行,以确保该值与输入字段中的值匹配。试图围绕PHP密码围绕盐/加密

此代码检查,看看该行存在:

$res = mysql_query("SELECT * FROM `users` WHERE `username` = '".$username."' AND `password` = '".$password."'"); 
        $num = mysql_num_rows($res); 
        //check if there was not a match 
        if($num == 0){ 
         //if not display error message 
         echo "<center>The <b>Password</b> you supplied does not match the one for that username!</center>"; 

我感到困惑实施盐业体制改革。我将如何改变这个脚本来检查加密的密码?我还没有找到一个很好的教程,详细解释了这一点。

回答

2

盐是一组字符添加到开始或加密和unencryption之前密码的最终使其更难运行蛮力攻击。

您首先创建的盐只是一个随机固定的一系列字符,然后在将其加密之前将其添加到密码中。在将数据放入查询之前,您还应该转义您的数据以防止MySQL注入攻击。

入关时到数据库

$username = mysql_real_escape_string($_POST['username']); 
$password = mysql_real_escape_string($_POST['pass']); 
$pass_hash = md5($SALT.$password); 
mysql_query(*query to insert $username and $pass_hash into db*) 

要检查密码是否正确

$username = mysql_real_escape_string($_POST['username']); 
$password = mysql_real_escape_string($_POST['pass']); 
$res = mysql_query(*query to extract $pass_hash from db where username==$username) 
//get the password from the $res and put it in a var 
if(md5($SALT.$pass_hash_from_db) == $password){*correct pass*} else {*invalid login*} 

设置$ SALT一些大的随机静态的字符串,比如$盐=“WEHGFHAWEOIfjo做到这一点; cewrxq#$%“;

+0

谢谢,这很有道理。 – user978905

0

如果用户注册并将其保存在数据库中,您将不得不生成新的salt。

// you save this in the database 
$encPass = encFunction($password.$salt); 

当某个用户想要登录时,检查该密码是否是该用户的密码列。

注:
- encFunction是你的加密功能

+0

我想我主要想知道的是 - 什么是盐?它只是一个连接到sha1哈希的随机字符串?我应该组成一个常量随机的9个字符的字符串并将其添加到哈希中,然后对密码检查做同样的事情吗?我是否正确思考这个问题? – user978905

+0

是的;它应该是完全随机的东西。 – MasterCassim