Encrypt and Decrypt files using PHP

Today, We want to share with you php encrypt file.In this post we will show you php encryption and decryption code, hear for php encryption library we will give you demo and example for implement.In this post, we will learn about JavaScript Client Side Password Hashing And Encryption with an example.

PHP – file encryption/decryption

In my recent website I have implemented step by step PDF file encryption and decryption. In this website, all the data is very useful and sensitive therefor to high security and protect all the files from unauthorized access as well as to keep them safe as well as secure i have used file based encryption/decryption best way. In this post, I will learn you how to encrypt/decrypt files using PHP.

i am going to use “Mcrypt” php extension file to encrypt/decrypt files format using a given key as well as some salt vector, therefor please 100% make sure Mcrypt is with your main PHP instillation. If you do not have this extension, step by step install it first, Here is Best way – install Mcrypt Extension

Here is the PHP function for encrypt file.

function encrypt_file($file, $destination, $all_arguments) {
     
	$handle = fopen($file, "rb") or die("sorry, Could not open a file."); 

	$contents = fread($handle, filesize($file));
 
	fclose($handle); 

	$iv = substr(md5("\x1B\x3C\x58".$all_arguments, true), 0, 8);
	$key = substr(md5("\x2D\xFC\xD8".$all_arguments, true) . md5("\x2D\xFC\xD9".$all_arguments, true), 0, 24);
	$opts = array('iv'=>$iv, 'key'=>$key);
	$fp = fopen($destination, 'wb') or die("Sorry, Could not open file for writing.");

	stream_filter_append($fp, 'mcrypt.tripledes', STREAM_FILTER_WRITE, $opts); 

	fwrite($fp, $contents) or die("sorry, Could not write to file."); 

	fclose($fp); 
 
}
  • Open the file and returns a file pointer resource.
  • Returns the read string.
  • Close the opened file pointer.
  • Add the Mcrypt stream filter with Triple DES
  • Write content in the destination file.
  • Close the opened file pointer.

Here is the function for decrypt. 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 above function as shown below.


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


$pass_decrypted = decrypt_file('/path/to/file','YOUR_SECRATE_FILE');
header('Content-type: application/pdf');
fpassthru($pass_decrypted);

How to encrypt/decrypt files with php (mcrypt)?

The mcrypt extension is deprecated in PHP 7.1.0 and removed in PHP 7.2.0. Instead, it is recommended to use the openssl extension which provides more secure encryption methods.

Here’s an example of how to encrypt and decrypt a file using the openssl extension in PHP:

// Encryption function
function encryptFile($inputFile, $outputFile, $key) {
    $data = file_get_contents($inputFile);
    $ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
    $iv = openssl_random_pseudo_bytes($ivlen);
    $ciphertext_raw = openssl_encrypt($data, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
    $hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
    $ciphertext = base64_encode( $iv.$hmac.$ciphertext_raw );
    file_put_contents($outputFile, $ciphertext);
}

// Decryption function
function decryptFile($inputFile, $outputFile, $key) {
    $ciphertext = file_get_contents($inputFile);
    $ciphertext = base64_decode($ciphertext);
    $ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
    $iv = substr($ciphertext, 0, $ivlen);
    $hmac = substr($ciphertext, $ivlen, $sha2len=32);
    $ciphertext_raw = substr($ciphertext, $ivlen+$sha2len);
    $original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
    $calcmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
    if (hash_equals($hmac, $calcmac)) {
        file_put_contents($outputFile, $original_plaintext);
    }
}

// Example usage
$key = 'my-secret-key';
$inputFile = 'path/to/input/file';
$encryptedFile = 'path/to/encrypted/file';
$decryptedFile = 'path/to/decrypted/file';

// Encrypt file
encryptFile($inputFile, $encryptedFile, $key);

// Decrypt file
decryptFile($encryptedFile, $decryptedFile, $key);

In the code above, we define two functions: encryptFile and decryptFile. The encryptFile function takes an input file path, output file path, and encryption key as parameters. It reads the content of the input file, generates a random initialization vector (IV), encrypts the data using the AES-128-CBC cipher, and appends the IV and a message authentication code (MAC) to the encrypted data. The resulting ciphertext is then base64-encoded and written to the output file.

The decryptFile function takes an input file path, output file path, and encryption key as parameters. It reads the content of the input file, decodes the base64-encoded ciphertext, extracts the IV and MAC, decrypts the data using the same cipher and key, and verifies the MAC to ensure the integrity of the decrypted data. If the MAC is valid, the decrypted data is written to the output file.

To use these functions, you need to provide a key that will be used for encryption and decryption. You can also specify the input, encrypted, and decrypted file paths. You can call the encryptFile function to encrypt a file, and then call the decryptFile function to decrypt it.

I hope you get an idea about php encrypt file.
I would like to have feedback on my
infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment