我正在尝试获取上传的图像,加密图像,将其存储在MySQL中,然后在授权人员请求查看时将其解密以供显示。
这是我目前正在加密的方式:
$image = addslashes(file_get_contents($_FILES['users_image']['tmp_name']));
$enc_image = encrypt($image, "long secret random key");
然后我将$enc_image
存储在MySQL BLOB字段中。当我尝试解密并打印时,它是这样的:
$img = decrypt($rec['file'], "long secret random key");
echo '<img src="data:image/jpeg;base64,'.base64_encode($img).'"/>';
我正在使用来自this Stackoverflow answer的这段代码,我在输出中看到了解密的base-64文本,但是它没有通过HTML显示。这是一个示例加密图像尝试恢复:https://pastebin.com/miDCP3Gz
注意:我的“长秘密随机密钥”包括一个哈希随机唯一盐,但我确信我使用相同的字符串进行加密和解密。
知道为什么这不能正确显示?
标记:
<html>
<head><title>Picture</title></head>
<body>
<form enctype="multipart/form-data" action="file.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="600000" />
<input type="file" name="users_image"/>
<input type="submit" text="Upload">
</form>
<?
if($_SERVER['REQUEST_METHOD'] === 'POST')
{
$image = file_get_contents($_FILES['users_image']['tmp_name']);
//encrypt
$cipher = "aes-128-cbc";
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$key = openssl_random_pseudo_bytes(128);
$ciphertext = openssl_encrypt($image, $cipher, $key, $options=0, $iv);
//add to DB
$mysqli = mysqli_connect("localhost","testu","","test");
$query = "INSERT INTO blobtbl(pics) VALUES (\"" . addslashes($ciphertext) ."\")";
$mysqli->query($query);
$id = mysqli_insert_id($mysqli);
//retrieve from DB
$sql = "SELECT * FROM blobtbl WHERE id = $id";
$res = $mysqli->query($sql);
$row=mysqli_fetch_assoc($res);
$newciphertext = $row['pics'];
//decrpyt and display
$img = openssl_decrypt($newciphertext, $cipher, $key, $options=0, $iv);
echo '<img src="data:image/jpeg;base64,'.base64_encode($img).'"/>';
echo "<br>Did it work?";
}
?>
</body>
</html>
在加密阶段删除addslashes。