key = hash('sha256', getenv('ENCRYPT_KEY'), true);
$this->iv = random_bytes(openssl_cipher_iv_length('AES-256-CBC'));
}
// 加密文件
public function encryptFile(string $sourcePath, string $targetPath): bool
{
if (!file_exists($sourcePath)) {
return false;
}
$content = file_get_contents($sourcePath);
$encrypted = openssl_encrypt($content, 'AES-256-CBC', $this->key, 0, $this->iv);
// 把IV和加密内容一起存,解密的时候需要
file_put_contents($targetPath, base64_encode($this->iv . $encrypted));
return true;
}
}
// 生产环境加载器:放在项目根目录,不要和加密文件放一起
class EncryptedLoader
{
private $key;
public function __construct()
{
$this->key = hash('sha256', getenv('ENCRYPT_KEY'), true);
}
public function load(string $encryptedPath): void
{
if (!file_exists($encryptedPath)) {
throw new RuntimeException('File not found');
}
$raw = file_get_contents($encryptedPath);
$data = base64_decode($raw);
$ivLength = openssl_cipher_iv_length('AES-256-CBC');
$iv = substr($data, 0, $ivLength);
$encryptedContent = substr($data, $ivLength);
$decrypted = openssl_decrypt($encryptedContent, 'AES-256-CBC', $this->key, 0, $iv);
if ($decrypted === false) {
// 生产环境不要输出具体错误,防止被爆破密钥
throw new RuntimeException('Load failed');
}
eval($decrypted); // 实际项目中可以用更安全的执行方式,比如写入临时文件后require
}
}
// 使用示例:生产环境入口文件调用
try {
$loader = new EncryptedLoader();
// 加载加密的核心业务文件
$loader->load(__DIR__ . '/core/BillingService.php.enc');
// 正常执行业务逻辑
$billing = new BillingService();
$billing->processOrder();
} catch (Exception $e) {
// 统一错误提示,不泄露细节
echo 'System error, please contact admin';
}
对,这个代码是可运行的,而且符合实际场景,注意eval的部分可以加个注释说实际项目可以用更安全的,比如写入临时文件然后如需更完整的 PHP 代码保护与在线加密服务,可访问 https://article.vvxyz.com 了解更多。