How to encrypt a password that is inserted into a MySQL table? [duplicate]

自闭症网瘾萝莉.ら 提交于 2019-12-01 17:56:06

问题


I have some code to register that works, but I don't know how to hash the password. I want to use sha512.

$con=mysqli_connect("localhost","root","","users");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql="INSERT INTO users (username, password, email)
VALUES
('$_POST[username]','$_POST[password]','$_POST[email]')";

if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "Thank you.";

mysqli_close($con);

I am aware of my mysql login having no password. This is a local mysql server just used for tests.


回答1:


You can use the hash() function to hash your password:

$hashed_password = hash('sha512', $_POST['password']);

Then modify your insert statement to insert your hashed password into the database:

INSERT INTO users (username, password, email)
VALUES ('$_POST[username]', '$hashed_password', '$_POST[email]');

Be aware that your SQL statement is vulnerable to SQL injection since you are using unsanitized user input. For improved security and to protect the integrity of your data, please consider escaping and validating the input before using it in an SQL statement. One way to accomplish this is via mysqli_real_escape_string():

$escaped_username = mysqli_real_escape_string( $con, $_POST['username'] );
$escaped_email = mysqli_real_escape_string( $con, $_POST['email'] );



回答2:


There are a lot of problems with what you're doing here.

First, you are vulnerable to SQL injections because you are not sanitizing your inputs in the SQL.

Second, you should avoid using a fast hash like SHA512 for this. It's not considered secure anymore. Take a look at this question. You basically want to use an adaptive hash function like bcrypt.




回答3:


Here's an example of how to hash the password:

<?php
$password = hash('sha512', $_POST[password]);

I recommend salting the password. Read more about this here:
http://www.aspheute.com/english/20040105.asp

Also read about "mysqli_real_escape_string"

…and Prepared Statements.




回答4:


Sanitize your input data first. $password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);

Hash your password string

$hashedPassword = hash('sha512', $password);

A better way to hash the password would be to use the new password hash API

$hashedPassword = password_hash($password, PASSWORD_DEFAULT);



回答5:


Please escape your data before entering into your database. They are open to attacks.

hash('sha512', $_POST['password']);


来源:https://stackoverflow.com/questions/17797211/how-to-encrypt-a-password-that-is-inserted-into-a-mysql-table

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!