使用 MCrypt 加密和解密檔案
Mcrypt 函式庫提供了 PHP 中加密和解密操作的函數。以下是如何使用它來加密和解密檔案的範例:
// 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); } }
重要說明:
以上是如何在 PHP 中使用 OpenSSL 對檔案進行加密和解密?的詳細內容。更多資訊請關注PHP中文網其他相關文章!