Binary data not stored properly in MySQL

回眸只為那壹抹淺笑 提交于 2019-12-04 07:09:46

问题


I want to store a base64_encoded string as binary data. So use base64_decode() on the string before inserting in a LONGBLOB field of MySQL. So far so good, however when I retrieve the data from MySQL, I can't generate the correct base64_encoded string which I have started with...

How is this possible? Thanks in advance

EDIT

The stored data is an encrypted string with AES-256CBC OPENSSL encryption routine.

CODE

For my code I use OpenSSL to encrypt a string

$string = "Test";
$IV = "1234567890123456";
$key = "12345678901234561234567890123456";
$encrypted = openssl_encrypt($string, "AES-256-CBC", $key, false, $IV);

$encrypted string is stored in LONGBLOB field by 
$sql_insert_data = $mysqli->prepare("INSERT INTO `TBLName` (String) Values(?)");
$sql_insert_data->bind_param('s', $mysqli->real_escape_string($encrypted));

//Thereafter, it is retrieved by a select statement
$decrypted = openssl_decrypt($row['String'], "AES-256-CBC", $key, true, $IV);

When I do base64_encode on the string and store that as a TEXT value in the DB, the above works. However, when I do not, the above does not work...

Thanks


回答1:


You are using prepared statements incorrectly:

$sql_insert_data->bind_param('s', $mysqli->real_escape_string($encrypted));
                                           ^^^^^^^^^^^^^^^^^^ :-!

Your code will add random backslashes to the binary stream. You don't need real_escape_string() at all.




回答2:


"damn son, the question is how to I optimize the storage of base64_encoded data successfully in mysql. That's all." -- See https://stackoverflow.com/a/42080296/1766831



来源:https://stackoverflow.com/questions/42064646/binary-data-not-stored-properly-in-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!