method));
$encrypted = openssl_encrypt($phpCode, $this->method, $this->key, 0, $iv);
// 把IV和加密内容拼接,存储为.enc.php文件
return '';
}
// 解密执行加密后的代码
public function runEncrypted(string $encFilePath): void
{
if (!file_exists($encFilePath)) {
die('加密文件不存在');
}
// 先做文件完整性校验
$this->checkIntegrity($encFilePath);
// 引入加密文件,获取IV和加密内容
include $encFilePath;
$iv = hex2bin($iv);
$decrypted = openssl_decrypt($enc, $this->method, $this->key, 0, $iv);
if ($decrypted === false) {
die('解密失败,文件可能被篡改');
}
// 执行解密后的代码
eval($decrypted);
}
// 文件哈希校验,防止篡改
private function checkIntegrity(string $filePath): void
{
$hashFile = $filePath . '.hash';
if (!file_exists($hashFile)) {
// 首次运行生成哈希
$currentHash = hash_file('sha256', $filePath);
file_put_contents($hashFile, $currentHash);
return;
}
$currentHash = hash_file('sha256', $filePath);
$storedHash = file_get_contents($hashFile);
if ($currentHash !== $storedHash) {
// 实际生产应该发告警,这里直接终止
die('核心文件被篡改,程序终止运行');
}
}
}
// 使用示例:加密核心业务代码
$protector = new CodeProtector();
$coreCode = file_get_contents('./core/pay_callback.php'); // 核心支付回调代码
$encryptedContent = $protector->encryptCode($coreCode);
file_put_contents('./protected/pay_callback.enc.php', $encryptedContent);
// 生产环境运行时调用runEncrypted执行加密后的代码即可
?>
对,这个代码是可运行的,而且实用,展示了加密和完整性校验。
然后是总结与建议,要落地:1. 不要依赖单一防护,要分层:混淆+加密+完整性校验+部署限制;2. 核心密钥不要硬编码,要从配置中心或者环境变量读取,不要提交到代码仓库;3. 定期做如需更完整的 PHP 代码保护与在线加密服务,可访问 https://article.vvxyz.com 了解更多。