【发布时间】:2020-07-23 05:30:28
【问题描述】:
我正在尝试制作一个人们可以聊天的程序,并且我想加密正在发送的消息。为此我有 2 个脚本,一个是 sendtext.php,另一个是 getchat.php。
所以我的问题是如何加密在一个文件中发送的文本,然后解密将在另一个文件中发送回的消息。
到目前为止,我的加密工作正常,但我不知道如何在其他文件中解密。 此外,如果您知道一种更安全的方法,我们将不胜感激。
sendtext.php
$username = $_POST["name"];
$text = $_POST["message"];
$key = openssl_random_pseudo_bytes(32, $cstrong);
$cipher = "aes-128-gcm";
if (in_array($cipher, openssl_get_cipher_methods()))
{
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext = openssl_encrypt($text, $cipher, $key, $options=0, $iv, $tag);
echo "Encrytped: " . $ciphertext;
//store $cipher, $iv, and $tag for decryption later
//$original_text = openssl_decrypt($ciphertext, $cipher, $key, $options=0, $iv, $tag);
//echo $original_text."\n";
}
//Add text to the table
$inserttextquery = "INSERT INTO ".$username." (username, message)
VALUES ('$username', '$ciphertext');";
mysqli_query($con, $inserttextquery) or die("#: send text failed");
getchat.php
$username = $_POST["name"];
$sql = "SELECT username, message FROM ".$username."";
$result = $con->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["username"] . "\t" . $row["message"] . "\t";
}
}
【问题讨论】:
-
这段代码很容易受到 SQL 注入攻击,如果还没有被黑客入侵,将被黑客入侵。加密是您最不必担心的事情。
-
每个用户都有一张桌子?您不应该像这样构建数据库。很快就会一团糟。有一个
users表并将所有用户存储在那里。然后是其他表中的 userid(一个自动递增的列)。 -
@user3783243 你能详细说明一下吗?我有一个包含所有用户的表(具有 id 自动增量和所有用户)。是的,我为每个用户提供了一张表,用于将他们的聊天记录存储在另一个数据库(称为 userchats)中。我怎样才能让它变得更好?
-
有一个
users表有userid, username, hashedpass, etc有userid自动增量,这样你就不会遇到竞争案例/冲突。然后你可以做类似select ... from messages where userid = ?这样的事情,你会得到一个用户的所有消息。您当前的方式将数据分散在数千个表中......索引文本也比整数更昂贵。
标签: php mysql encryption