如何加密插入到MySQL表中的密码? [英] How to encrypt a password that is inserted into a MySQL table?

查看:160
本文介绍了如何加密插入到MySQL表中的密码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码可以注册,但我不知道如何散列密码。我想用sha512。

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);

我知道我的mysql登录没有密码。这是一个只用于测试的本地mysql服务器。

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

推荐答案

您可以使用 / code>函数来加密你的密码:

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

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

然后修改您的insert语句以将散列的密码插入到数据库中:

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]');

请注意,由于您使用了未经过处理的用户输入,因此您的SQL语句容易受到SQL注入的攻击。为了提高安全性并保护数据的完整性,请在使用SQL语句之前考虑转义和验证输入。一种方法是通过 mysqli_real_escape_string()

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'] );

这篇关于如何加密插入到MySQL表中的密码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆