2017-09-25 15 views
0

我試圖將上傳的圖像,加密圖像,存儲在MySQL中,然後在授權人員請求查看時將其解密以供顯示。使用PHP加密圖像以存儲在MySQL BLOB中,然後解密並打印

這裏是我當前如何加密:

$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,和我看到解密的基礎-64的文字,在我的輸出,但它不通過HTML顯示。這裏是一個示例加密圖像的嘗試被恢復:https://pastebin.com/miDCP3Gz

注意:我的「長祕密隨機密鑰」包括一個哈希隨機獨特的鹽,但我相信我是使用相同的字符串進行加密和解密。

任何想法爲什麼這將不會正確顯示?

回答

1

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

     //retireve 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。

+0

當我刪除它甚至沒有正確插入數據庫。 – Bing

+0

什麼是Apache錯誤日誌或BD錯誤日誌?你的加密庫或方法是什麼? –

相關問題