PHP项目文件加密如何PHP代码实现

wen PHP项目 24

本文目录导读:

PHP项目文件加密如何PHP代码实现

  1. 使用 PHP 内置函数进行简单编码
  2. 使用开源加密库
  3. 使用专业 PHP 加密扩展
  4. 完整的 PHP 代码加密方案(Obfuscation)
  5. 运行时代码加密(Runtime Encryption)
  6. 多层加密方案(推荐)
  7. 注意事项
  8. 建议

在PHP项目中实现代码加密有多种方式,以下提供几种实用方案:

使用 PHP 内置函数进行简单编码

Base64 编码/解码

<?php
// 编码
$encoded = base64_encode('你的PHP代码');
echo $encoded;
// 解码
$decoded = base64_decode($encoded);
eval($decoded); // 执行解码后的代码
?>

使用 gzcompress/gzuncompress

<?php
// 压缩加密
$code = 'echo "Hello World";';
$compressed = gzcompress($code, 9);
$encoded = base64_encode($compressed);
// 解密执行
$decoded = base64_decode($encoded);
$decompressed = gzuncompress($decoded);
eval($decompressed);
?>

使用开源加密库

PHP-JavaScript-AES 加密(推荐使用 php-seclib)

<?php
// 安装依赖
// composer require phpseclib/phpseclib
use phpseclib3\Crypt\AES;
use phpseclib3\Crypt\Random;
function encryptCode($code, $password) {
    $aes = new AES('cbc');
    $aes->setPassword($password);
    $iv = Random::string($aes->getBlockLength() >> 3);
    $aes->setIV($iv);
    $encrypted = $aes->encrypt($code);
    return base64_encode($iv . $encrypted);
}
function decryptCode($encryptedData, $password) {
    $data = base64_decode($encryptedData);
    $aes = new AES('cbc');
    $aes->setPassword($password);
    $iv = substr($data, 0, 16);
    $encrypted = substr($data, 16);
    $aes->setIV($iv);
    return $aes->decrypt($encrypted);
}
// 使用示例
$code = 'echo "This is secret code";';
$encrypted = encryptCode($code, 'mysecretpassword123');
echo "加密后: " . $encrypted . "\n";
// 解密并执行
$decrypted = decryptCode($encrypted, 'mysecretpassword123');
eval($decrypted);
?>

使用专业 PHP 加密扩展

SourceGuardian(商业方案)

<?php
// SourceGuardian 配置文件示例
// 需要安装 SourceGuardian 扩展
// 在代码中添加加密标记
// <?php 
// @include_once('sourceguardian.php');
// 
// 或者购买 SourceGuardian Loader 进行加密
?>

IonCube(商业方案)

<?php
// IonCube 加密示例
// 需要在服务器安装 IonCube Loader
// 使用 ioncube 命令行工具加密
// ioncube_encoder.sh /path/to/your/php/files
?>

完整的 PHP 代码加密方案(Obfuscation)

<?php
class CodeObfuscator {
    private $encryptionKey;
    private $useEval = true;
    public function __construct($key = null) {
        $this->encryptionKey = $key ?: md5(uniqid(mt_rand(), true));
    }
    public function encryptFile($inputFile, $outputFile = null) {
        $code = file_get_contents($inputFile);
        $encrypted = $this->encryptCode($code);
        if ($outputFile === null) {
            $outputFile = $inputFile . '.encrypted.php';
        }
        // 生成解密加载器
        $loader = $this->generateLoader($encrypted);
        file_put_contents($outputFile, $loader);
        return $outputFile;
    }
    private function encryptCode($code) {
        // 移除PHP标签
        $code = preg_replace('/^<\?php\s*/', '', $code);
        $code = preg_replace('/\s*\?>\s*$/', '', $code);
        // 压缩代码
        $code = $this->minifyPHP($code);
        // 加密
        $encrypted = openssl_encrypt(
            $code,
            'aes-256-cbc',
            $this->encryptionKey,
            0,
            substr(md5($this->encryptionKey), 0, 16)
        );
        return base64_encode($encrypted);
    }
    private function generateLoader($encryptedData) {
        $key = $this->encryptionKey;
        $salt = substr(md5($key), 0, 16);
        $loader = <<<LOADER
<?php
// 加密代码解密加载器
\$encrypted = '{$encryptedData}';
\$key = '{$key}';
\$salt = '{$salt}';
// 解密函数
function __decrypt(\$data, \$key, \$salt) {
    \$encrypted = base64_decode(\$data);
    \$decrypted = openssl_decrypt(
        \$encrypted,
        'aes-256-cbc',
        \$key,
        0,
        \$salt
    );
    return \$decrypted;
}
// 执行解密后的代码
eval(__decrypt(\$encrypted, \$key, \$salt));
?>
LOADER;
        return $loader;
    }
    private function minifyPHP($code) {
        // 简单压缩
        $code = preg_replace('/\/\/.*?(\n|$)/', '', $code);
        $code = preg_replace('/\/\*.*?\*\//s', '', $code);
        $code = preg_replace('/\s+/', ' ', $code);
        $code = preg_replace('/\s*([\{\}\(\)\[\];,:\.=])\s*/', '$1', $code);
        return trim($code);
    }
}
// 使用示例
$obfuscator = new CodeObfuscator('your-secure-key-here');
$inputFile = 'original.php';
$outputFile = $obfuscator->encryptFile($inputFile);
echo "加密文件生成: $outputFile\n";
// 解密并执行的版本
function executeEncryptedFile($encryptedFile) {
    include($encryptedFile);
}
?>

运行时代码加密(Runtime Encryption)

<?php
class RuntimeEncryptor {
    private static $instance = null;
    private $key;
    private $loaded = [];
    private function __construct($key = null) {
        $this->key = $key ?: getenv('APP_SECRET_KEY') ?: 'default-key-change-me';
    }
    public static function getInstance($key = null) {
        if (self::$instance === null) {
            self::$instance = new self($key);
        }
        return self::$instance;
    }
    public function encryptFile($file, $preservePath = true) {
        if (!file_exists($file)) {
            throw new Exception("File not found: $file");
        }
        $code = file_get_contents($file);
        $code = preg_replace('/^<\?php\s*/', '', $code);
        // 使用 XXTEA 算法(简单但有效)
        $encrypted = $this->xxteaEncrypt($code, $this->key);
        $base64Encrypted = base64_encode($encrypted);
        // 生成加密后的文件
        $outputPath = $preservePath ? $file . '.enc' : $file;
        $loaderCode = "<?php\n// Encrypted by RuntimeEncryptor\n// DO NOT MODIFY\n\n\$__encrypted = '{$base64Encrypted}';\n\$__key = '{$this->key}';\n\nfunction __decr(\$data, \$key) {\n    \$decoded = base64_decode(\$data);\n    \$result = '';\n    for(\$i=0; \$i<strlen(\$decoded); \$i++) {\n        \$result .= chr(ord(\$decoded[\$i]) ^ ord(\$key[\$i % strlen(\$key)]));\n    }\n    return \$result;\n}\n\neval(__decr(\$__encrypted, \$__key));\n?>";
        file_put_contents($outputPath, $loaderCode);
        return $outputPath;
    }
    private function xxteaEncrypt($data, $key) {
        $v = $this->strToLongs($data);
        $k = $this->strToLongs($key);
        if (count($k) < 4) {
            $k = array_pad($k, 4, 0);
        }
        $n = count($v) - 1;
        $z = $v[$n];
        $y = $v[0];
        $delta = 0x9E3779B9;
        $q = floor(6 + 52 / ($n + 1));
        $sum = 0;
        while ($q-- > 0) {
            $sum = ($sum + $delta) & 0xFFFFFFFF;
            $e = ($sum >> 2) & 3;
            for ($p = 0; $p < $n; $p++) {
                $y = $v[$p + 1];
                $mx = ($z >> 5 ^ $y << 2) + (($y >> 3 ^ $z << 4) ^ ($sum ^ $y))
                    + ($k[($p & 3) ^ $e] ^ $z);
                $z = $v[$p] = ($v[$p] + $mx) & 0xFFFFFFFF;
            }
            $y = $v[0];
            $mx = ($z >> 5 ^ $y << 2) + (($y >> 3 ^ $z << 4) ^ ($sum ^ $y))
                + ($k[($n & 3) ^ $e] ^ $z);
            $z = $v[$n] = ($v[$n] + $mx) & 0xFFFFFFFF;
        }
        return $this->longsToStr($v);
    }
    private function strToLongs($s) {
        $len = strlen($s);
        $v = [];
        for ($i = 0; $i < $len; $i += 4) {
            $v[] = ord($s[$i]) | (ord($s[$i+1]) << 8) | (ord($s[$i+2]) << 16) | (ord($s[$i+3]) << 24);
        }
        return $v;
    }
    private function longsToStr($v) {
        $s = '';
        foreach ($v as $value) {
            $s .= chr($value & 0xFF);
            $s .= chr(($value >> 8) & 0xFF);
            $s .= chr(($value >> 16) & 0xFF);
            $s .= chr(($value >> 24) & 0xFF);
        }
        return $s;
    }
}
// 使用示例
$encryptor = RuntimeEncryptor::getInstance('your-secret-key');
$result = $encryptor->encryptFile('your-php-file.php');
echo "文件已加密: $result\n";
?>

多层加密方案(推荐)

<?php
class MultiLayerEncryptor {
    private $layers = ['aes', 'xor', 'base64'];
    private $keys;
    public function __construct($keys = null) {
        $this->keys = $keys ?: [
            'aes' => md5('layer-1-key'),
            'xor' => md5('layer-2-key'),
            'base64' => md5('layer-3-key')
        ];
    }
    public function encryptCode($code) {
        // 第一层:压缩和混淆变量名
        $code = $this->obfuscateVariables($code);
        $code = $this->minifyCode($code);
        // 第二层:AES加密
        $aesEncrypted = openssl_encrypt(
            $code,
            'aes-256-cbc',
            $this->keys['aes'],
            0,
            substr($this->keys['aes'], 0, 16)
        );
        // 第三层:XOR加密
        $xorEncrypted = '';
        for ($i = 0; $i < strlen($aesEncrypted); $i++) {
            $xorEncrypted .= chr(ord($aesEncrypted[$i]) ^ ord($this->keys['xor'][$i % strlen($this->keys['xor'])]));
        }
        // 第四层:Base64编码
        return base64_encode($xorEncrypted);
    }
    public function decryptCode($encryptedCode) {
        // 反向解密
        $base64Decoded = base64_decode($encryptedCode);
        $xorDecrypted = '';
        for ($i = 0; $i < strlen($base64Decoded); $i++) {
            $xorDecrypted .= chr(ord($base64Decoded[$i]) ^ ord($this->keys['xor'][$i % strlen($this->keys['xor'])]));
        }
        $aesDecrypted = openssl_decrypt(
            $xorDecrypted,
            'aes-256-cbc',
            $this->keys['aes'],
            0,
            substr($this->keys['aes'], 0, 16)
        );
        return $aesDecrypted;
    }
    private function obfuscateVariables($code) {
        // 简单的变量名混淆
        $code = preg_replace_callback('/\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)/', function($matches) {
            return '$_' . dechex(crc32($matches[1]));
        }, $code);
        return $code;
    }
    private function minifyCode($code) {
        // 移除注释和多余空格
        $code = preg_replace('/\/\*.*?\*\//s', '', $code);
        $code = preg_replace('/\/\/.*?(\n|$)/', '', $code);
        $code = preg_replace('/\s+/', ' ', $code);
        return trim($code);
    }
}
// 使用示例
$encryptor = new MultiLayerEncryptor();
// 原始代码
$originalCode = '<?php echo "Hello World"; ?>';
// 加密
$encrypted = $encryptor->encryptCode(explode('<?php', $originalCode)[1]);
echo "原始代码: " . $originalCode . "\n";
echo "加密后: " . $encrypted . "\n";
// 解密并执行
$decrypted = $encryptor->decryptCode($encrypted);
eval($decrypted);
?>

注意事项

  1. 安全性:以上方法提供的都是代码混淆和简单加密,不是绝对安全
  2. 性能影响:加密和解密过程会增加执行时间
  3. 调试困难:加密后的代码难以调试和排错
  4. 兼容性:某些加密方法可能不兼容所有 PHP 环境
  5. 法律合规:确保您的加密行为符合相关法律法规

建议

  • 对于高安全性需求,建议使用商业解决方案(如 IonCube、SourceGuardian)
  • 结合文件权限控制、服务器安全配置
  • 在部署环境中使用 HTTPS 和安全的数据库连接
  • 定期更新加密密钥
  • 测试加密后的代码在目标环境中的兼容性

选择哪种加密方案取决于您的具体需求、安全级别要求和预算限制。

抱歉,评论功能暂时关闭!