php 如何在 mysql 中创建和存储 md5 密码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6781931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I create and store md5 passwords in mysql
提问by maestro416
Probably a very newbie question but, Ive been reading around and have found some difficulty in understanding the creation and storage of passwords. From what i've read md5/hash passwords are the best ways to store them in a database. However, how would I go about creating those passwords in the first place?
可能是一个非常新手的问题,但是,我一直在阅读并发现在理解密码的创建和存储方面存在一些困难。从我所读到的 md5/hash 密码是将它们存储在数据库中的最佳方式。但是,首先我将如何创建这些密码?
So say I have a login page with user bob, and password bob123 - how will I 1. get bobs password into the database to begin with (hashed) 2. how do I retrive and confirm the hashed password?
所以说我有一个用户 bob 和密码 bob123 的登录页面 - 我将如何 1. 将 bob 密码输入数据库以开始(散列) 2. 我如何检索并确认散列密码?
Thanks
谢谢
回答by JohnKlehm
Edit 2017/11/09: Be sure to take a look at the answer from O Jones.
编辑 2017/11/09:一定要看看 O Jones 的回答。
First off MD5 isn't the greatest hashing method you could use for this try sha256 or sha512
首先,MD5 不是您可以用于此尝试的最佳散列方法 sha256 或 sha512
That said lets use hash('sha256')
instead of md5()
to represent the hashing part of the process.
也就是说,让我们使用hash('sha256')
而不是md5()
来表示过程的散列部分。
When you first create a username and password you will hash the raw password with some salt (some random extra characters added to each password to make them longer/stronger).
当您第一次创建用户名和密码时,您将使用一些盐(向每个密码添加一些随机额外字符以使其更长/更强)散列原始密码。
Might look something like this coming in from the create user form:
可能看起来像这样来自创建用户表单:
$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'); ";
Then on login it'll look something like this:
然后在登录时它看起来像这样:
$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
回答by Dalen
you have to reason in terms of hased password:
您必须根据密码进行推理:
store the password as md5('bob123');
when bob is register to your app
将密码存储为md5('bob123');
bob 注册到您的应用程序时的密码
$query = "INSERT INTO users (username,password) VALUES('bob','".md5('bob123')."');
then, when bob is logging-in:
然后,当 bob 登录时:
$query = "SELECT * FROM users WHERE username = 'bob' AND password = '".md5('bob123')."';
obvioulsy use variables for username and password, these queries are generated by php and then you can execute them on mysql
显然,用户名和密码使用变量,这些查询是由 php 生成的,然后您可以在 mysql 上执行它们
回答by O. Jones
Please don't use MD5 for password hashing. Such passwords can be cracked in milliseconds. You're sure to be pwned by cybercriminals.
请不要使用 MD5 进行密码散列。这样的密码可以在几毫秒内破解。您肯定会被网络犯罪分子利用。
PHP offers a high-quality and future proof password hashing subsystembased on a reliable random salt and multiple rounds of Rijndael / AES encryption.
PHP 提供了一个基于可靠随机盐和多轮 Rijndael / AES 加密的高质量和面向未来的密码哈希子系统。
When a user first provides a password you can hash it like this:
当用户第一次提供密码时,您可以像这样散列它:
$pass = 'whatever the user typed in';
$hashed_password = password_hash( "secret pass phrase", PASSWORD_DEFAULT );
Then, store $hashed_password
in a varchar(255)
column in MySQL. Later, when the user wants to log in, you can retrieve the hashed password from MySQL and compare it to the password the user offered to log in.
然后,存储在 MySQL 的$hashed_password
一varchar(255)
列中。稍后,当用户想要登录时,您可以从 MySQL 中检索散列密码并将其与用户提供的登录密码进行比较。
$pass = 'whatever the user typed in';
$hashed_password = 'what you retrieved from MySQL for this user';
if ( password_verify ( $pass , $hashed_password )) {
/* future proof the password */
if ( password_needs_rehash($hashed_password , PASSWORD_DEFAULT)) {
/* recreate the hash */
$rehashed_password = password_hash($pass, PASSWORD_DEFAULT );
/* store the rehashed password in MySQL */
}
/* password verified, let the user in */
}
else {
/* password not verified, tell the intruder to get lost */
}
How does this future-proofing work? Future releases of PHP will adapt to match faster and easier to crack encryption. If it's necessary to rehash passwords to make them harder to crack, the future implementation of the password_needs_rehash()
function will detect that.
这种面向未来的工作如何运作?PHP 的未来版本将适应更快更容易破解加密的匹配。如果有必要重新散列密码以使其更难破解,该password_needs_rehash()
功能的未来实现 将检测到这一点。
Don't reinvent the flat tire. Use professionally designed and vetted open source code for security.
不要重新发明爆胎。使用经过专业设计和的开源代码来确保安全。
回答by Marc B
Insertion:
插入:
INSERT INTO ... VALUES ('bob', MD5('bobspassword'));
retrieval:
恢复:
SELECT ... FROM ... WHERE ... AND password=md5('hopefullybobspassword');
is how'd you'd do it directly in the queries. However, if your MySQL has query logging enabled, then the passwords' plaintext will get written out to this log. So... you'd want to do the MD5 conversion in your script, and then insert that resulting hash into the query.
是您如何直接在查询中执行此操作。但是,如果您的 MySQL 启用了查询日志记录,那么密码的明文将写入此日志。所以...您想在脚本中进行 MD5 转换,然后将生成的哈希值插入到查询中。
回答by Lucian
Why don't you use the MySQL built in password hasher:
为什么不使用 MySQL 内置的密码哈希器:
http://dev.mysql.com/doc/refman/5.1/en/password-hashing.html
http://dev.mysql.com/doc/refman/5.1/en/password-hashing.html
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
for comparison you could something like this:
为了比较,你可以是这样的:
select id from PassworTable where Userid='<userid>' and Password=PASSWORD('<password>')
and if it returns a value then the user is correct.
如果它返回一个值,那么用户是正确的。
回答by Smokefoot
PHP has a method called md5 ;-) Just $password = md5($passToEncrypt);
PHP 有一个方法叫做 md5 ;-) Just $password = md5($passToEncrypt);
If you are searching in a SQL u can use a MySQL Method MD5() too....
如果您在 SQL 中搜索,您也可以使用 MySQL 方法 MD5()....
SELECT * FROM user WHERE Password='. md5($password) .'
or SELECT * FROM ser WHERE Password=MD5('. $password .')
或 SELECT * FROM ser WHERE Password=MD5('. $password .')
To insert it u can do it the same way.
要插入它,你可以用同样的方式来做。
回答by Taimur
I'm not amazing at PHP, but I think this is what you do:
我对 PHP 并不擅长,但我认为这就是你所做的:
$password = md5($password)
$password = md5($password)
and $password
would be the $_POST['password']
or whatever
并且$password
将是$_POST['password']
或其他
回答by B.S.B.
To increase security even more, You can have md5 encryption along with two different salt strings, one static salt defined in php file and then one more randomly generated unique salt for each password record.
为了进一步提高安全性,您可以使用 md5 加密以及两个不同的盐字符串,一个在 php 文件中定义的静态盐,然后为每个密码记录随机生成一个唯一的盐。
Here is how you can generate salt, md5 string and store:
以下是生成盐、md5 字符串和存储的方法:
$unique_salt_string = hash('md5', microtime());
$password = hash('md5', $_POST['password'].'static_salt'.$unique_salt_string);
$query = "INSERT INTO users (username,password,salt) VALUES('bob','".$password."', '".$unique_salt_string."');
Now you have a static salt, which is valid for all your passwords, that is stored in the .php file. Then, at registration execution, you generate a unique hash for that specific password.
现在你有一个静态盐,它对你的所有密码都有效,它存储在 .php 文件中。然后,在注册执行时,您会为该特定密码生成一个唯一的哈希值。
This all ends up with: two passwords that are spelled exactly the same, will have two different hashes. The unique hash is stored in the database along with the current id. If someone grab the database, they will have every single unique salt for every specific password. But what they don't have is your static salt, which make things a lot harder for every "hacker" out there.
这一切都以:两个拼写完全相同的密码将具有两个不同的哈希值。唯一的哈希值与当前 id 一起存储在数据库中。如果有人获取数据库,他们将拥有每个特定密码的每个唯一盐。但是他们没有的是您的静态盐,这使每个“黑客”的工作变得更加困难。
This is how you check the validity of your password on login.php for example:
这是您在 login.php 上检查密码有效性的方法,例如:
$user = //username input;
$db_query = mysql_query("SELECT salt FROM users WHERE username='$user'");
while($salt = mysql_fetch_array($db_query)) {
$password = hash('md5',$_POST['userpassword'].'static_salt'.$salt[salt]);
}
This method is very powerful and secure. If you want to use sha512 encryption, just to put that inside the hash function instead of md5 in above code.
这种方法非常强大且安全。如果你想使用 sha512 加密,只需将它放在哈希函数中,而不是上面代码中的 md5。
回答by Faisal Shaikh
just get the hash by following line and store it into the database:
只需通过以下行获取哈希并将其存储到数据库中:
$encryptedValue = md5("YOUR STRING");