r/PHPhelp • u/HyveUK • Sep 18 '17
Php Database - Content Encryption / Decryption
Hello Reddit!
I'm working on a website that will input data into a Database, and the data itself is rather sensitive. As a precaution I want to have some Encryption / Decryption occur, and while I have had success in some basic testing, it's not currently working when I try to pull the data from the Database itself.
Here is what I currently have working;
$plaintext = 'Hello World';
$encrypted = openssl_encrypt($plaintext, $cipher, $key, 0, $iv);
$decrypted = openssl_decrypt($encrypted, $cipher, $key, 0, $iv);
echo "<pre>" . $encrypted . " - Encrypted Version </pre>";
echo "<pre>" . $decrypted . " - Decrypted Version </pre>";This works just fine on the page itself. When trying to input it into the Database, and retrieve it and Decrypt however, it stops working.
I can see the data inside the Database is encrypted, and I can echo out the results normally, however, when I attempt to use a mysqli_fetch_array() to loop through and retrieve the data, the same functionality that works just above, no longer works..
while($row = mysqli_fetch_array($result))
{
$title = openssl_decrypt($row['title'], $cipher, $key, 0, $iv);
echo "<pre>" . $title . " - Decrypted Version (MySQLi) </pre>";
}Do note that the connection to the Database for the loop is working, as I can output the raw data itself. It's just through the openssl_decrypt that it no longer works.
I'm stumped for what's the cause, I have looked through a plethora of Stack Overflow questions on this, and many other online sources, but none of them are related to my problem.
I thank you for taking the time to read, and look forward to working through this issue.
You can also track the Stack Overflow conversation here: https://stackoverflow.com/questions/46281075/php-database-content-encryption-decryption
6
u/scootstah Sep 18 '17
The data is probably getting mutated because of the encoding on the table column. You can verify this by hashing the data before the INSERT and then again after a SELECT, and compare the values.
To fix that you either need to use a binary data type in the table, or base64 encode the data first.
1
u/cyrusol Sep 19 '17
I do think binary would be the semantically correct choice in this scenario of those two.
2
u/WarInternal Sep 18 '17
What version of mysql are you on? You might have built in commands for this:
https://dev.mysql.com/doc/refman/5.5/en/encryption-functions.html#function_aes-encrypt