Encrypt files in PHP

Have you ever think of encrypting your secret files yourself? If you dunno how to do it yourself, here’s the rescue! In this article, I’ll teach you how to encrypt/decrypt files entirely in PHP!

First, please make sure Mcrypt is with your PHP bundle. If you don’t have this extension, please install it first as we need this to encrypt/decrypt files.

Then, it’s time to code! The code is pretty short as it uses the Mcrypt stream filter which also brings a huge performance increase when handling large files.

<?php
// The password
$passphrase = 'My secret';

// Turn a human readable passphrase
// into a reproducible iv/key pair

$iv = substr(md5("\x1B\x3C\x58".$passphrase, true), 0, 8);
$key = substr(md5("\x2D\xFC\xD8".$passphrase, true) .
md5("\x2D\xFC\xD9".$passphrase, true), 0, 24);
$opts = array('iv' => $iv, 'key' => $key, 'mode' => 'stream');

// Open the file
$fp = fopen('secret-file.enc', 'wb');

// Add the Mcrypt stream filter
// We use Triple DES here, but you
// can use other encryption algorithm here
stream_filter_append($fp, 'mcrypt.tripledes', STREAM_FILTER_WRITE, $opts);

// Wrote some contents to the file
fwrite($fp, 'Secret secret secret data');

// Close the file
fclose($fp);

This is the code that encrypt contents written into the files. Isn’t this pretty short?┬áBut, how can I make the contents readable again? Here’s the way to decrypt the files:

<?php
// The password
$passphrase = 'My secret';

// Turn a human readable passphrase
// into a reproducible iv/key pair

$iv = substr(md5("\x1B\x3C\x58".$passphrase, true), 0, 8);
$key = substr(md5("\x2D\xFC\xD8".$passphrase, true) .
md5("\x2D\xFC\xD9".$passphrase, true), 0, 24);
$opts = array('iv' => $iv, 'key' => $key, 'mode' => 'stream');

// Open the file
$fp = fopen('secret-file.enc', 'rb');

// Add the Mcrypt stream filter
// We use Triple DES here, but you
// can use other encryption algorithm here
stream_filter_append($fp, 'mdecrypt.tripledes', STREAM_FILTER_READ, $opts);

// Read the file contents
fpassthru($content);

Now we have a nice and easy solution to keep things secret in PHP. (Just to make sure, you need to change $passphrase into your very own password and keep it secret.)

7 Replies to “Encrypt files in PHP”

  1. Hi Licson,
    I am not that much familiar with file encryption/decryption in php,
    I just want to know, Is it possible to encrypt/decrypt PDF file content using above code?
    Please guide me on this.
    Thank you.

    1. Any file is encrypted in the same manner. This method will work for any file. However, if your PHP gets exposed, intruders will be able to see your encryption key. It is much safer to do the encryption serverside. If your server is running linux, you can use openssl.

Leave a Reply

Your email address will not be published. Required fields are marked *