PHP加密授权源码解析与应用

```html PHP加密授权源码解析与应用

PHP加密授权源码解析与应用

在SaaS服务、商业插件或私有API分发场景中,基于PHP的轻量级加密授权机制可有效防止未授权使用。本文解析一种安全、实用的授权验证方案——结合RSA非对称加密与时间戳签名,不依赖外部服务,适合中小项目快速集成。

核心设计思路

授权文件(license.key)为JSON格式,包含:domain(绑定域名)、expires(过期时间戳)、signature(RSA签名)。服务端仅用公钥验签,私钥由开发者离线保管,杜绝密钥泄露风险。

生成授权文件(开发环境执行)

<?php
// generate_license.php —— 仅在本地运行!
$privateKey = openssl_pkey_get_private('file://private_key.pem');
$data = json_encode([
    'domain' => 'example.com',
    'expires' => strtotime('+30 days')
], JSON_UNESCAPED_UNICODE);

openssl_sign($data, $signature, $privateKey, OPENSSL_ALGO_SHA256);
$license = [
    'domain' => 'example.com',
    'expires' => strtotime('+30 days'),
    'signature' => base64_encode($signature)
];
file_put_contents('license.key', json_encode($license, JSON_PRETTY_PRINT));
echo "✅ 授权文件已生成:license.key\n";
?>

服务端授权验证(部署代码)

<?php
// auth.php —— 集成到业务入口
function verifyLicense(): bool {
    $licensePath = __DIR__ . '/license.key';
    if (!file_exists($licensePath)) return false;

    $license = json_decode(file_get_contents($licensePath), true);
    if (!$license || !isset($license['domain'], $license['expires'], $license['signature'])) {
        return false;
    }

    // 1. 域名绑定校验
    $currentDomain = $_SERVER['HTTP_HOST'] ?? '';
    if ($license['domain'] !== $currentDomain) return false;

    // 2. 过期时间校验
    if (time() > $license['expires']) return false;

    // 3. RSA签名验证(使用公钥)
    $publicKey = openssl_pkey_get_public('file://public_key.pem');
    $data = json_encode([
        'domain' => $license['domain'],
        'expires' => $license['expires']
    ], JSON_UNESCAPED_UNICODE);

    $isValid = openssl_verify(
        $data,
        base64_decode($license['signature']),
        $publicKey,
        OPENSSL_ALGO_SHA256
    ) === 1;

    openssl_pkey_free($publicKey);
    return $isValid;
}

// 使用示例
if (!verifyLicense()) {
    http_response_code(403);
    die("❌ 授权验证失败:请检查 license.key 或联系技术支持");
}
echo "✅ 授权有效,系统正常运行";
?>
⚠️ 安全提示:
  • 私钥(private_key.pem)严禁上传至服务器或版本库;
  • 公钥(public_key.pem)可安全部署,但建议混淆路径;
  • 生产环境应配合OPcache与文件权限限制(如 chmod 400 license.key)。

该方案平衡了安全性与易用性:无需数据库、不调用远程接口、签名不可篡改。开发者可进一步扩展字段(如最大并发数、功能模块开关),通过JSON结构灵活控制授权策略。真正的加密授权,始于严谨的设计,而非复杂的黑盒。

```