Binary data not stored properly in MySQL

2019-03-07 11:05发布

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

2条回答
Lonely孤独者°
2楼-- · 2019-03-07 11:28

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.

查看更多
Root(大扎)
3楼-- · 2019-03-07 11:45

"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

查看更多
登录 后发表回答