Encrypting and Decrypting Files with MCrypt
The Mcrypt library provides functions for encryption and decryption operations in PHP. Here's an example of how to use it for encrypting and decrypting files:
// ENCRYPT FILE function encryptFile() { $key = generateKey(); // Function to generate a secure encryption key $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-128-cbc')); // Generate a random initialization vector $plaintext = file_get_contents(PATH . '/ftpd/' . $file); $encrypted = openssl_encrypt($plaintext, 'aes-128-cbc', $key, OPENSSL_RAW_DATA, $iv); $encryptedFile = fopen(PATH . '/encrypted/' . $file . '.txt', 'w'); fwrite($encryptedFile, $iv . $encrypted); fclose($encryptedFile); unlink(PATH . '/ftpd/' . $file); } // DECRYPT FILE function decryptFile() { $key = generateKey(); // Function to generate the same encryption key used in encryption if ($handle = opendir(PATH . '/encrypted')) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { $encryptedFile = fopen(PATH . '/encrypted/' . $file, 'r'); $encryptedData = fread($encryptedFile, filesize(PATH . '/encrypted/' . $file)); $iv = substr($encryptedData, 0, openssl_cipher_iv_length('aes-128-cbc')); $decrypted = openssl_decrypt(substr($encryptedData, openssl_cipher_iv_length('aes-128-cbc')), 'aes-128-cbc', $key, OPENSSL_RAW_DATA, $iv); $decryptedFile = fopen(PATH . '/decrypted/' . $file, 'w'); fwrite($decryptedFile, $decrypted); fclose($decryptedFile); // unlink(PATH . '/encrypted/' . $file); } } closedir($handle); } }
Important notes:
The above is the detailed content of How Can I Encrypt and Decrypt Files Using OpenSSL in PHP?. For more information, please follow other related articles on the PHP Chinese website!