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

I have a registration code that works, but I don't know how the hash password is. 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 know that my mysql login does not have a password. This is a local mysql server that is just used for tests.

+4
source share
5 answers

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

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

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

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

Remember that your SQL statement is vulnerable to SQL injection, since you are using unanitated user input. To increase security and protect the integrity of your data, please consider shielding and validating your input before using it in an SQL statement. One way to achieve this is through mysqli_real_escape_string() :

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

There are many problems with what you are doing here.

First, you are vulnerable to SQL injections because you do not deactivate your SQL inputs.

Secondly, you should avoid using a fast hash like SHA512. It is no longer considered safe. Take a look at this question . You basically want to use an adaptive hash function like bcrypt.

+3
source

Here is an example of how a hash password is:

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

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

Also read about " mysqli_real_escape_string "

& hellip; Prepared reports .

+2
source

First sanitize your input. $ password = filter_input (INPUT_POST, 'password', FILTER_SANITIZE_STRING);

Hash your password string

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

The best way to hashed a password is to use a new password hash

 $hashedPassword = password_hash($password, PASSWORD_DEFAULT); 
+1
source

Please avoid data before entering your database. They are open to attack.

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

Source: https://habr.com/ru/post/1492793/


All Articles