我有一个表单,将它们插入数据库。我使用open ssl加密图像,然后将它们存储在数据库中。
我也解密它们并显示它们。从数据库中取出然后解密后,图像不会显示。
我似乎无法找出图像没有显示的原因。从我可以看到他们正在正确插入数据库
<?php
if(isset($_POST["action"]))
{
$connect = mysqli_connect("","","","");
$cipher = "aes-128-cbc";
$ivlen = openssl_cipher_iv_length($cipher);
$key = openssl_random_pseudo_bytes(128);
if($_POST["action"] == "fetch")
{
$query = "SELECT * FROM tbl_images where r_id = '".$_POST["r_id"]."' ORDER BY id DESC";
$result = mysqli_query($connect, $query);
$output = '
<table class="table table-bordered table-striped">
<tr>
<th width="10%">ID</th>
<th width="70%">Image</th>
<th width="10%">Remove</th>
</tr>
';
while($row = mysqli_fetch_array($result))
{
$newciphertext = $row["name"];
$newiv = $row["iv"];
$img = openssl_decrypt($newciphertext, $cipher, $key, $options=0, $newiv);
$output .= '
<tr>
<td>'.$row["id"].'</td>
<td>
<a target="_blank" href="#" onClick="enlarge(this)""><img src="data:image/jpeg;base64,'.base64_encode($img).'" class="img-thumbnail"/></a>
</td>
<td><button type="button" name="delete" class="btn btn-danger bt-xs delete" id="'.$row["id"].'">Remove</button></td>
</tr>
';
}
$output .= '</table>';
echo $output;
}
if($_POST["action"] == "insert")
{
$file = file_get_contents($_FILES["image"]["tmp_name"]);
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext = openssl_encrypt($file, $cipher, $key, $options=0, $iv);
$query = "INSERT INTO tbl_images(name, r_id, iv) VALUES ('\"" . addslashes($ciphertext) ."\"', '".$_POST["r_id"]."', '$iv')";
if(mysqli_query($connect, $query))
{
echo 'Image Inserted into Database';
}
}
if($_POST["action"] == "delete")
{
$query = "DELETE FROM tbl_images WHERE id = '".$_POST["image_id"]."'";
if(mysqli_query($connect, $query))
{
echo 'Image Deleted from Database';
}
}
}
?>
答案 0 :(得分:1)
每次访问此页面时,都会计算一个新的$iv
,这对加密部分很好,但您需要使用相同的$iv
来解密图像。因此,当您尝试解密图像时,您的错误$iv
并且解密失败。您应该在数据库中将$iv
保存在新字段中,或者与加密图像连接。