Class: PHP OpenSSL Encrypt and Decrypt File This class can encrypt and decrypt file data using OpenSSL. It takes a given password and encrypts data read from a file using the OpenSSL extension. The class can also decrypt previously encrypted files using the same password. Example #!/usr/bin/env php -e|-d * * @author Martin Latter * @copyright Martin Latter 20/02/2018 * @version 0.05 * @license GNU GPL v3.0 * @link https://github.com/Tinram/OpenSSL-File-Encrypt.git */ declare(strict_types=1); define('DUB_EOL', PHP_EOL . PHP_EOL); define('LINUX', (stripos(php_uname(), 'linux') !== FALSE) ? TRUE : FALSE); if ( ! extension_loaded('openssl')) { die(PHP_EOL . ' OpenSSL library not available!' . DUB_EOL); } require('classes/openssl_file.class.php'); $sUsage = PHP_EOL . ' ' . basename(__FILE__, '.php') . DUB_EOL . "\tusage: php " . basename(__FILE__) . ' -e|-d ' . ( ! LINUX ? '' : '') . DUB_EOL; $sMode = null; $aOptions = getopt('h::e::d::', ['help::', 'h::']); if ( ! empty($aOptions)) { $sOpt = key($aOptions); switch ($sOpt) { case 'h': die($sUsage); break; case 'e': case 'd': $sMode = $sOpt; break; } } else { die($sUsage); } if ( ! isset($_SERVER['argv'][2])) { echo PHP_EOL . ' missing filename!' . PHP_EOL; die($sUsage); } $sFilename = $_SERVER['argv'][2]; if ( ! file_exists($sFilename)) { die(PHP_EOL . ' \'' . $sFilename . '\' does not exist in this directory!' . DUB_EOL); } if (LINUX) { echo ' password: '; `/bin/stty -echo`; $sPassword = trim(fgets(STDIN)); `/bin/stty echo`; if ($sMode === 'e') { echo PHP_EOL . ' re-enter password: '; `/bin/stty -echo`; $sPassword2 = trim(fgets(STDIN)); `/bin/stty echo`; if ($sPassword !== $sPassword2) { die(PHP_EOL . ' entered passwords do not match!' . DUB_EOL); } } } else { if ( ! isset($_SERVER['argv'][3])) { die(PHP_EOL . ' missing password!' . DUB_EOL . "\tusage: " . basename(__FILE__) . ' -e|-d ' . DUB_EOL); } else { $sPassword = $_SERVER['argv'][3]; } } if ($sMode === 'e') { echo OpenSSLFile::encrypt($sFilename, $sPassword); } else if ($sMode === 'd') { echo OpenSSLFile::decrypt($sFilename, $sPassword); }