如何在mysql中创建和存储md5密码

可能是一个非常新手的问题,但我一直在阅读,发现在理解密码的创建和存储方面有些困难。从我读过的内容中,md5 /

hash密码是将其存储在数据库中的最佳方法。但是,我将如何首先创建这些密码?

因此,说我有一个登录页面,其中包含用户bob和密码bob123-我将如何1.将bobs密码输入数据库(以哈希开头)2.如何获取并确认哈希密码?

谢谢

回答:

编辑2017/11/09:请务必查看O Jones的回答。

首先,MD5并不是您可以在此尝试使用的最出色的哈希方法sha256或sha512

就是说让我们使用hash('sha256')而不是md5()代表流程的哈希部分。

首次创建用户名和密码时,您将使用一些盐对原始密码进行哈希处理(在每个密码中添加了一些随机的额外字符,以使它们变长/变强)。

可能看起来像这样,来自创建用户表单:

$escapedName = mysql_real_escape_string($_POST['name']); # use whatever escaping function your db requires this is very important.

$escapedPW = mysql_real_escape_string($_POST['password']);

# generate a random salt to use for this account

$salt = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));

$saltedPW = $escapedPW . $salt;

$hashedPW = hash('sha256', $saltedPW);

$query = "insert into user (name, password, salt) values ('$escapedName', '$hashedPW', '$salt'); ";

然后在登录时,它将类似于以下内容:

$escapedName = mysql_real_escape_string($_POST['name']);

$escapedPW = mysql_real_escape_string($_POST['password']);

$saltQuery = "select salt from user where name = '$escapedName';";

$result = mysql_query($saltQuery);

# you'll want some error handling in production code :)

# see http://php.net/manual/en/function.mysql-query.php Example #2 for the general error handling template

$row = mysql_fetch_assoc($result);

$salt = $row['salt'];

$saltedPW = $escapedPW . $salt;

$hashedPW = hash('sha256', $saltedPW);

$query = "select * from user where name = '$escapedName' and password = '$hashedPW'; ";

# if nonzero query return then successful login

以上是 如何在mysql中创建和存储md5密码 的全部内容, 来源链接: utcz.com/qa/426814.html

回到顶部