萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP RSA 非對稱加密完整指南:金鑰生成、加解密、簽名驗簽與實戰應用

RSA 基礎概念

概念說明
公鑰公開分發,用於加密資料或驗證簽名
私鑰嚴格保密,用於解密資料或產生簽名
加密場景客戶端用公鑰加密 → 伺服端用私鑰解密 (機密性)
簽名場景伺服端用私鑰簽名 → 客戶端用公鑰驗證 (完整性/不可否認性)
填充模式PKCS#1 v1.5 (舊)、OAEP (新、推薦加密)、PSS (推薦簽名)

金鑰生成 (OpenSSL CLI)

# 1. 生成 2048 位 RSA 私鑰 (PKCS#1 格式)
openssl genrsa -out private_key.pem 2048

# 2. 轉換為 PKCS#8 格式 (現代標準,無加密)
openssl pkcs8 -topk8 -inform PEM -in private_key.pem -outform PEM -nocrypt -out private_key_pkcs8.pem

# 3. 從私鑰導出公鑰
openssl rsa -in private_key.pem -pubout -out public_key.pem

# 4. 查看金鑰資訊
openssl rsa -in private_key.pem -text -noout
openssl rsa -in public_key.pem -pubin -text -noout

PHP 完整實現類

<?php
class RsaCrypto {
    private $privateKey;
    private $publicKey;
    private $keyResource = [];
    
    public function __construct(string $privateKeyPath = '', string $publicKeyPath = '') {
        if ($privateKeyPath) $this->loadPrivateKey($privateKeyPath);
        if ($publicKeyPath) $this->loadPublicKey($publicKeyPath);
    }
    
    public function loadPrivateKey(string $path): bool {
        $content = file_get_contents($path);
        if (!$content) return false;
        $this->privateKey = $content;
        $this->keyResource['private'] = openssl_pkey_get_private($content);
        return $this->keyResource['private'] !== false;
    }
    
    public function loadPublicKey(string $path): bool {
        $content = file_get_contents($path);
        if (!$content) return false;
        $this->publicKey = $content;
        $this->keyResource['public'] = openssl_pkey_get_public($content);
        return $this->keyResource['public'] !== false;
    }
    
    // 字串資源 ID 檢查
    public function isValid(): bool {
        return !empty($this->keyResource['private']) || !empty($this->keyResource['public']);
    }
    
    /**
     * 公鑰加密 (資料長度限制:key_size/8 - 11 for PKCS1, -42 for OAEP)
     * @param string $data 明文
     * @param int $padding OPENSSL_PKCS1_PADDING (預設) | OPENSSL_OAEP_PADDING
     * @return string|false Base64 編碼密文
     */
    public function publicEncrypt(string $data, int $padding = OPENSSL_PKCS1_PADDING) {
        if (empty($this->keyResource['public'])) return false;
        $encrypted = '';
        $ok = openssl_public_encrypt($data, $encrypted, $this->keyResource['public'], $padding);
        return $ok ? base64_encode($encrypted) : false;
    }
    
    /**
     * 私鑰解密
     */
    public function privateDecrypt(string $base64Encrypted, int $padding = OPENSSL_PKCS1_PADDING) {
        if (empty($this->keyResource['private'])) return false;
        $decrypted = '';
        $ok = openssl_private_decrypt(base64_decode($base64Encrypted), $decrypted, $this->keyResource['private'], $padding);
        return $ok ? $decrypted : false;
    }
    
    /**
     * 私鑰加密 (簽名用途,實際簽名請用 sign())
     */
    public function privateEncrypt(string $data, int $padding = OPENSSL_PKCS1_PADDING) {
        if (empty($this->keyResource['private'])) return false;
        $encrypted = '';
        $ok = openssl_private_encrypt($data, $encrypted, $this->keyResource['private'], $padding);
        return $ok ? base64_encode($encrypted) : false;
    }
    
    /**
     * 公鑰解密 (驗證簽名用途,實際驗證請用 verify())
     */
    public function publicDecrypt(string $base64Encrypted, int $padding = OPENSSL_PKCS1_PADDING) {
        if (empty($this->keyResource['public'])) return false;
        $decrypted = '';
        $ok = openssl_public_decrypt(base64_decode($base64Encrypted), $decrypted, $this->keyResource['public'], $padding);
        return $ok ? $decrypted : false;
    }
    
    /**
     * 簽名 (推薦使用 SHA256 + PSS 填充)
     * @param string $data 待簽名資料
     * @param string $algo 簽名演算法 'sha256', 'sha512', 'sha1'
     * @return string|false Base64 編碼簽名
     */
    public function sign(string $data, string $algo = 'sha256') {
        if (empty($this->keyResource['private'])) return false;
        $signature = '';
        $ok = openssl_sign($data, $signature, $this->keyResource['private'], $algo);
        return $ok ? base64_encode($signature) : false;
    }
    
    /**
     * 驗證簽名
     */
    public function verify(string $data, string $base64Signature, string $algo = 'sha256') {
        if (empty($this->keyResource['public'])) return false;
        return openssl_verify($data, base64_decode($base64Signature), $this->keyResource['public'], $algo) === 1;
    }
    
    /**
     * 大數據分段加密 (混合加密:AES 加密資料 + RSA 加密 AES Key)
     */
    public function hybridEncrypt(string $data): array {
        // 生成隨機 AES-256 Key + IV
        $aesKey = random_bytes(32);
        $iv = random_bytes(16);
        
        // AES-256-CBC 加密資料
        $encryptedData = openssl_encrypt($data, 'aes-256-cbc', $aesKey, OPENSSL_RAW_DATA, $iv);
        if ($encryptedData === false) throw new Exception('AES encryption failed');
        
        // RSA 加密 AES Key
        $encryptedKey = $this->publicEncrypt($aesKey, OPENSSL_OAEP_PADDING);
        if (!$encryptedKey) throw new Exception('RSA key encryption failed');
        
        return [
            'key' => $encryptedKey,      // RSA 加密的 AES Key
            'iv' => base64_encode($iv),  // IV 可公開
            'data' => base64_encode($encryptedData)
        ];
    }
    
    public function hybridDecrypt(array $package): string {
        $aesKey = $this->privateDecrypt($package['key'], OPENSSL_OAEP_PADDING);
        if (!$aesKey) throw new Exception('RSA key decryption failed');
        
        $decrypted = openssl_decrypt(
            base64_decode($package['data']), 
            'aes-256-cbc', 
            $aesKey, 
            OPENSSL_RAW_DATA, 
            base64_decode($package['iv'])
        );
        if ($decrypted === false) throw new Exception('AES decryption failed');
        
        return $decrypted;
    }
    
    public function __destruct() {
        foreach ($this->keyResource as $res) {
            if (is_resource($res)) openssl_free_key($res);
        }
    }
}

// 使用範例
$rsa = new RsaCrypto('private_key_pkcs8.pem', 'public_key.pem');

// 1. 基本加解密 (短資料)
$original = '敏感資料:信用卡號 4242-4242-4242-4242';
$encrypted = $rsa->publicEncrypt($original, OPENSSL_OAEP_PADDING);
$decrypted = $rsa->privateDecrypt($encrypted, OPENSSL_OAEP_PADDING);
echo "加密: $encrypted\n解密: $decrypted\n\n";

// 2. 簽名驗簽
$signature = $rsa->sign($original);
$valid = $rsa->verify($original, $signature);
echo "簽名: $signature\n驗證: " . ($valid ? '通過' : '失敗') . "\n\n";

// 3. 混合加密 (長資料/檔案)
$longData = str_repeat("大量業務資料...", 1000);
$package = $rsa->hybridEncrypt($longData);
$restored = $rsa->hybridDecrypt($package);
echo "混合加密解密 " . ($restored === $longData ? "成功" : "失敗") . "\n";

關鍵限制與避坑

⚠ 關鍵限制:
  • 資料長度限制:RSA 直接加密資料長度 < KeySize/8 - PaddingOverhead。2048-bit key:PKCS1 最大 245 bytes,OAEP 最大 190 bytes
  • 必須用混合加密:大資料請用 AES 加密,RSA 只加密 AES Key
  • 填充模式必須一致:加解密、簽名驗簽雙方必須協商相同 padding/algo
  • Base64 編碼傳輸:密文含二進位資料,網路傳輸必須 Base64
  • 私鑰檔案權限:chmod 600 private_key.pem,嚴禁提交版控

實戰應用場景

1. API 介面簽名驗證 (防篡改)

// 客戶端簽名
$signStr = "GET\n/api/v1/users\n" . http_build_query(['page'=>1, 'limit'=>20]);
$signature = $rsa->sign($signStr);
// Header: Authorization: RSA-SHA256 Credential=client_id, Signature=$signature

// 伺服端驗證
if (!$rsa->verify($signStr, $signature)) {
    http_response_code(401);
    die('Invalid signature');
}

2. 敏感配置加密儲存

// 部署時用公鑰加密敏感配置
$encryptedDbPass = $rsa->publicEncrypt($dbPassword, OPENSSL_OAEP_PADDING);
// 配置檔存 base64 密文
// 運行時用私鑰解密
$dbPassword = $rsa->privateDecrypt($config['encrypted_db_pass'], OPENSSL_OAEP_PADDING);

3. 授權碼/許可證系統

// 產生授權碼:私鑰簽名 {user_id, expires, features}
$payload = json_encode(['uid'=>12345, 'exp'=>'2025-12-31', 'features'=>['pro','api']]);
$license = $rsa->sign($payload) . '.' . base64_encode($payload);

// 驗證授權碼
list($sig, $payloadB64) = explode('.', $license, 2);
$payload = base64_decode($payloadB64);
if ($rsa->verify($payload, $sig)) {
    $data = json_decode($payload, true);
    if (strtotime($data['exp']) > time()) { /* 授權有效 */ }
}

總結

PHP RSA 核心 API:openssl_pkey_get_private/public、openssl_public_encrypt/private_decrypt、openssl_sign/verify。生產環境必須注意:金鑰長度≥2048、使用 OAEP/PSS 填充、大資料用混合加密、私鑰嚴格保護。建議封裝為服務類並整合 DI 容器管理金鑰生命週期。

copyright © 萬盛學電腦網 all rights reserved