Search code examples
phpfileencryptionphp-openssl

Encrypting strings write to file and then decrypt file in PHP


I'm having a slight problem where I am using "openssl_encrypt" to encrypt a string of text that contains HTML, writing that string to a file, and then in a separate page, I am decrypting the entire file using "openssl_decrypt". I've made sure to use the same encryption key, same method, and same iv. I imagine this is something that, as a newbie to encryption, I just can't see. Thank you in advance for any help!

Here is some example code:

//An example of the string
$string = "<div class='mod'><div><span class='datetimestamp'>On 06/28/2016 at 04:32:09 PM, ** modified a record with id of \"5\" in the \"results\" table:</span><br><span class='record-label'>Prev Record:</span>jobnumber='none', dropdate='07/06/2016', eventdate='07/16/2016', dealership='ABC Nissan', pieces='3700', datatype='DB', letter='t'";

//The encryption
$encrypt = openssl_encrypt($string, 'AES-256-XTS', '93jkak3rzp72', 1, '45gh354687ls0349');
$file = fopen("logs/2016-06-28.log", 'a');
fwrite($file, $encrypt);
fclose($file);


//The decryption - DONE IN A SEPARATE PAGE
$file = @fopen("logs/2016-06-28.log", "r");
if ($file) {
    while (($data = fgets($file)) !== false) {
        $decrypt .= openssl_decrypt($data, 'AES-256-XTS', '93jkak3rzp72', 1, '45gh354687ls0349');
    }
}

Solution

  • Perhaps the issue is that you are trying to append additional encrypted data, that will not generally work for several reasons, a major one being that AES is block based and there will most likely be padding. Many modes use some form of chaining and this will also fail when appending encrypted data.

    You are opening the file you are writing to in append mode, that is not what you need, instead use write w mode. That is causing each encryption to be appended to the previous data and the reason the first tie works but subsequent times. If you examine the file length after each encryption it will be apparent what is happening.

    You need to use:

    $file = fopen("logs/2016-06-28.log", 'w');
    

    From the php fopen docs:

    'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

    'a' Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() has no effect, writes are always appended.