使用PHP加密图像以便在MySQL BLOB中存储然后解密和打印

问题描述 投票:0回答:2

我正在尝试获取上传的图像,加密图像,将其存储在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

注意:我的“长秘密随机密钥”包括一个哈希随机唯一盐,但我确信我使用相同的字符串进行加密和解密。

知道为什么这不能正确显示?

php mysql encryption cryptography blob
2个回答
3
投票
  1. 确保您的图像足够小或存储位置足够大。如果你有超过65kB的东西,你需要一个longblob而不是blob。任何超过这个大小的东西都会被截断并丢失。
  2. 在插入数据库之前将addslashes移动到右边,而不是在加密之前。单引号(或双引号,取决于您使用的名称)将字符串的开头和结尾指定给MySQL引擎。 addslashes函数可以转义这些和其他特殊字符,以防止它们混淆MySQL引擎。它在加密之前将记录添加到数据库的事实只是随机的。
  3. 您应该知道这些图像作为临时文件保存在服务器上。除非采取特殊预防措施,否则其中的数据将保留在HDD的松弛空间中。攻击者可以使用取证或恢复工具轻松检索它。

标记:

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

0
投票

在加密阶段删除addslashes。

© www.soinside.com 2019 - 2024. All rights reserved.