Full Stack LAMP - MEAN Developer, Python developer. Certified Azure Developer. Freelance programmer/consultant/trainer.

In my recent project, I implemented PDF file encryption and decryption. In this project, data is very sensitive so to protect files from unauthorized access and to keep them safe and secure we have used a file-based encryption/decryption method. In this article, I will teach you how to encrypt/decrypt files in PHP.

We gonna use the “Mcrypt” PHP extension to encrypt/decrypt files using a given key and salt vector, so please make sure Mcrypt is with your PHP installation. If you do not have this extension, please install it first, Here is a tutorial – How to install Mcrypt

Here is the function for encrypting files.

function encrypt_file($file, $destination, $passphrase) {
        // Open the file and returns a file pointer resource. 
	$handle = fopen($file, "rb") or die("Could not open a file."); 
        // Returns the read string.
	$contents = fread($handle, filesize($file));
        // Close the opened file pointer.
	fclose($handle); 

	$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);
	$fp = fopen($destination, 'wb') or die("Could not open file for writing.");
        // Add the Mcrypt stream filter with Triple DES
	stream_filter_append($fp, 'mcrypt.tripledes', STREAM_FILTER_WRITE, $opts); 
        // Write content in the destination file.
	fwrite($fp, $contents) or die("Could not write to file."); 
       // Close the opened file pointer.
	fclose($fp); 
 
}

Here is the function for decrypting. The decrypted data can be returned as a string or served for download.

function decrypt_file($file,$passphrase) {
	$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);
	$fp = fopen($file, 'rb');
	stream_filter_append($fp, 'mdecrypt.tripledes', STREAM_FILTER_READ, $opts);
	return $fp;
}

You can use the above function as shown below.

// encrypt file
encrypt_file('/path/to/file','./upload','secretPassword');

// Output to inline PDF
$decrypted = decrypt_file('/path/to/file','secretPassword');
header('Content-type: application/pdf');
fpassthru($decrypted);

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

0 0 votes
Article Rating
Subscribe
Notify of
guest

10 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments