File encryption and decryption in 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

  • PHP – file encryption/decryption
    • Related posts

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);

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.

I am Jaydeep Gondaliya , a software engineer, the founder and the person running Pakainfo. I’m a full-stack developer, entrepreneur and owner of Pakainfo.com. I live in India and I love to write tutorials and tips that can help to other artisan, a Passionate Blogger, who love to share the informative content on PHP, JavaScript, jQuery, Laravel, CodeIgniter, VueJS, AngularJS and Bootstrap from the early stage.

how to encrypt/decrypt files using just mcrypt and php standard functions?

Well, you don't want to use mcrypt. You want to use sodium these days.

Encrypting a File with Sodium (PHP 7.2+, PECL ext/sodium, or sodium_compat)

The relevant API you're looking for is crypto_secretstream.

const CUSTOM_CHUNK_SIZE = 8192;

/**
 * @ref https://stackoverflow.com/q/11716047
 */
function encryptFile(string $inputFilename, string $outputFilename, string $key): bool
{
    $iFP = fopen($inputFilename, 'rb');
    $oFP = fopen($outputFilename, 'wb');

    [$state, $header] = sodium_crypto_secretstream_xchacha20poly1305_init_push($key);

    fwrite($oFP, $header, 24); // Write the header first:
    $size = fstat($iFP)['size'];
    for ($pos = 0; $pos < $size; $pos += CUSTOM_CHUNK_SIZE) {
        $chunk = fread($iFP, CUSTOM_CHUNK_SIZE);
        $encrypted = sodium_crypto_secretstream_xchacha20poly1305_push($state, $chunk);
        fwrite($oFP, $encrypted, CUSTOM_CHUNK_SIZE + 17);
        sodium_memzero($chunk);
    }

    fclose($iFP);
    fclose($oFP);
    return true;
}

Decryption looks like this:

/**
 * @ref https://stackoverflow.com/q/11716047
 */
function decryptFile(string $inputFilename, string $outputFilename, string $key): bool
{
    $iFP = fopen($inputFilename, 'rb');
    $oFP = fopen($outputFilename, 'wb');

    $header = fread($iFP, 24);
    $state = sodium_crypto_secretstream_xchacha20poly1305_init_pull($header, $key);
    $size = fstat($iFP)['size'];
    $readChunkSize = CUSTOM_CHUNK_SIZE + 17;
    for ($pos = 24; $pos < $size; $pos += $readChunkSize) {
        $chunk = fread($iFP, $readChunkSize);
        [$plain, $tag] = sodium_crypto_secretstream_xchacha20poly1305_pull($state, $chunk);
        fwrite($oFP, $plain, CUSTOM_CHUNK_SIZE);
        sodium_memzero($plain);
    }
    fclose($iFP);
    fclose($oFP);
    return true;
}

Using the two functions together:

$key = random_bytes(32);
encryptFile('input.txt', 'cipher.txt', $key);
decryptFile('cipher.txt', 'decrypt.txt', $key);

How do I encrypt a PHP file?

3 Ways To Encrypt and Hide PHP Source Code.
Use a code obfuscator to make the source code difficult to read..
Use a code protector or encoder. Something like an alternative PHP engine, but with the ability to protect the source code..
Lastly, compile the PHP code using a converter or virtual machine..

What are encryption techniques in PHP?

PHP encryption is important to the privacy and safety of your data. In practical terms, PHP encryption uses algorithms (sometimes called hashing algorithms) to translate the “clear” data into encrypted text that requires very specific decryption processes to “decode” the data back to the clean version.

Which encryption is best for PHP?

Secret key encryption (or symmetric encryption as it's also known) uses a single key to both encrypt and decrypt data. In the past PHP relied on mcrypt and openssl for secret key encryption. PHP 7.2 introduced Sodium, which is more modern and widely considered more secure.

What encryptions are available in PHP?

Types of PHP Encryption.
Hashing. The Hashing Algorithm of the PHP Programming Language usually takes one input value and then transforms it into one message digest. ... .
Secret Key Encryption. The Secret Key Encryption of the PHP usually uses one single key to both encryption and decryption data. ... .
Envelope Encryption..