萬盛學電腦網

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

PHP 介面資料加解密與簽名驗證:AES/RSA 混合加密實戰(phpseclib)

API 介面傳輸敏感資料需**加密保密性**、**簽名保完整性**、**驗證防偽造**。業界標準做法:**AES 對稱加密資料本體 + RSA 非對稱加密 AES 金鑰 + RSA 簽名驗證**。本文以 phpseclib 3.x 示範完整流程,含金鑰管理、加解密、簽名驗證、常見坑點。

架構圖解

發送端                          接收端
  │                                │
  ├─ 生成隨機 AES-256 金鑰 + IV    │
  ├─ AES-GCM 加密資料 → 密文       │
  ├─ RSA-OAEP 加密 AES 金鑰 → 密鑰  │
  ├─ RSA-PSS 簽名(密文+時間戳)    │
  │                                │
  ▼                                ▼
┌─────────────────┐          ┌─────────────────┐
│  傳輸封包       │   HTTPS  │  解析封包       │
│ {               │ ──────►  │  1. 驗證簽名    │
│   "encrypted_key": "...",  │          2. RSA 解密 AES Key
│   "iv": "...",              │          3. AES-GCM 解密
│   "ciphertext": "...",      │          4. 驗證時間戳/Nonce
│   "signature": "...",       │
│   "timestamp": 1234567890   │
│ }                         │
└─────────────────┘          └─────────────────┘

環境準備

composer require phpseclib/phpseclib:~3.0

完整實作類別

<?php
declare(strict_types=1);

namespace App\Security;

use phpseclib3\Crypt\AES;
use phpseclib3\Crypt\RSA;
use phpseclib3\Crypt\Common\SymmetricKey;

class ApiCrypto
{
    private RSA $privateKey;   // 我方私鑰(解密 AES Key、簽名)
    private RSA $publicKey;    // 我方公鑰(供對方驗簽)
    private RSA $peerPublicKey; // 對方公鑰(加密 AES Key、驗簽)
    private int $aesKeyBits = 256;
    private int $timestampTolerance = 300; // 5 分鐘

    public function __construct(
        string $myPrivateKeyPem,
        string $myPublicKeyPem,
        string $peerPublicKeyPem
    ) {
        $this->privateKey = RSA::load($myPrivateKeyPem);
        $this->publicKey = RSA::load($myPublicKeyPem);
        $this->peerPublicKey = RSA::load($peerPublicKeyPem);

        // 統一設定:OAEP + SHA256、PSS + SHA256
        $this->privateKey->setEncryptionMode(RSA::ENCRYPTION_OAEP);
        $this->privateKey->setHash('sha256');
        $this->privateKey->setMGFHash('sha256');

        $this->peerPublicKey->setEncryptionMode(RSA::ENCRYPTION_OAEP);
        $this->peerPublicKey->setHash('sha256');
        $this->peerPublicKey->setMGFHash('sha256');

        $this->privateKey->setSignatureMode(RSA::SIGNATURE_PSS);
        $this->privateKey->setHash('sha256');
        $this->peerPublicKey->setSignatureMode(RSA::SIGNATURE_PSS);
        $this->peerPublicKey->setHash('sha256');
    }

    /** 加密封裝:回傳可直接 json_encode 的陣列 */
    public function encryptPayload(array|string $payload): array
    {
        $plaintext = is_array($payload) ? json_encode($payload, JSON_UNESCAPED_UNICODE) : $payload;
        $timestamp = time();
        $nonce = random_bytes(16);

        // 1. 生成隨機 AES 金鑰
        $aesKey = random_bytes($this->aesKeyBits / 8);

        // 2. AES-GCM 加密
        $aes = new AES('gcm');
        $aes->setKey($aesKey);
        $iv = random_bytes(12); // GCM 建議 12 bytes
        $aes->setNonce($iv);
        $ciphertext = $aes->encrypt($plaintext);
        $tag = $aes->getTag(); // GCM 認證標籤

        // 3. RSA-OAEP 加密 AES 金鑰
        $encryptedKey = $this->peerPublicKey->encrypt($aesKey);

        // 4. 簽名:保護密文完整性 + 防重放
        $signedData = $ciphertext . $iv . $tag . pack('N', $timestamp) . $nonce;
        $signature = $this->privateKey->sign($signedData);

        return [
            'v' => 1, // 版本
            'ek' => base64_encode($encryptedKey),
            'iv' => base64_encode($iv),
            'ct' => base64_encode($ciphertext),
            'tag' => base64_encode($tag),
            'ts' => $timestamp,
            'nonce' => base64_encode($nonce),
            'sig' => base64_encode($signature),
        ];
    }

    /** 解密驗證:成功回傳解密後資料(陣列/字串),失敗拋出例外 */
    public function decryptPayload(array $packet): array|string
    {
        // 版本相容
        if (($packet['v'] ?? 1) !== 1) {
            throw new \RuntimeException('Unsupported packet version');
        }

        // 1. 時間戳檢查(防重放)
        $ts = (int)($packet['ts'] ?? 0);
        if (abs(time() - $ts) > $this->timestampTolerance) {
            throw new \RuntimeException('Timestamp expired or invalid');
        }

        // 2. 解碼
        $encryptedKey = base64_decode($packet['ek'], true);
        $iv = base64_decode($packet['iv'], true);
        $ciphertext = base64_decode($packet['ct'], true);
        $tag = base64_decode($packet['tag'], true);
        $nonce = base64_decode($packet['nonce'], true);
        $signature = base64_decode($packet['sig'], true);

        if ($encryptedKey === false || $iv === false || $ciphertext === false || $tag === false || $nonce === false || $signature === false) {
            throw new \RuntimeException('Base64 decode failed');
        }

        // 3. 驗證簽名(用對方公鑰)
        $signedData = $ciphertext . $iv . $tag . pack('N', $ts) . $nonce;
        if (!$this->peerPublicKey->verify($signedData, $signature)) {
            throw new \RuntimeException('Signature verification failed');
        }

        // 4. RSA 解密 AES 金鑰
        $aesKey = $this->privateKey->decrypt($encryptedKey);
        if ($aesKey === false) {
            throw new \RuntimeException('RSA decryption failed');
        }

        // 5. AES-GCM 解密
        $aes = new AES('gcm');
        $aes->setKey($aesKey);
        $aes->setNonce($iv);
        $plaintext = $aes->decrypt($ciphertext);
        if ($plaintext === false) {
            throw new \RuntimeException('AES decryption failed');
        }
        if (!$aes->verifyTag($tag)) {
            throw new \RuntimeException('GCM tag verification failed (tampered)');
        }

        // 6. 嘗試 JSON 解析
        $decoded = json_decode($plaintext, true, 512, JSON_THROW_ON_ERROR);
        return json_last_error() === JSON_ERROR_NONE ? $decoded : $plaintext;
    }
}
?>

金鑰生成與管理

<?php
// 一次性生成 RSA-2048/4096 金鑰對
$rsa = new RSA();
$rsa->setKeyLength(2048); // 或 4096
extract($rsa->createKey());

// 私鑰(PKCS#8,含公鑰資訊)── 極機密,僅己方持有
file_put_contents('my_private.pem', $privatekey);
// 公鑰(PKCS#1/SPKI)── 可公開給對方
file_put_contents('my_public.pem', $publickey);
file_put_contents('peer_public.pem', $peerPublicKey); // 對方給你的公鑰
?>

使用範例

<?php
require 'vendor/autoload.php';
use App\Security\ApiCrypto;

$crypto = new ApiCrypto(
    file_get_contents('keys/my_private.pem'),
    file_get_contents('keys/my_public.pem'),
    file_get_contents('keys/peer_public.pem')
);

// 發送端
$payload = ['order_id' => '20240101001', 'amount' => 1234.56, 'currency' => 'TWD'];
$packet = $crypto->encryptPayload($payload);
$json = json_encode($packet);
// 透過 HTTPS POST 送出...

// 接收端
$received = json_decode(file_get_contents('php://input'), true);
try {
    $data = $crypto->decryptPayload($received);
    // $data = ['order_id' => '...', 'amount' => 1234.56, 'currency' => 'TWD']
    // 處理業務邏輯...
} catch (\Throwable $e) {
    http_response_code(400);
    error_log('API Crypto Error: ' . $e->getMessage());
    echo json_encode(['error' => 'Invalid request']);
}
?>

關鍵安全細節

  1. AES-GCM:提供機密性+完整性(認證標籤),取代舊式 CBC+HMAC。
  2. RSA-OAEP:抗選擇密文攻擊,優於 PKCS#1 v1.5。
  3. RSA-PSS:概率簽名,優於 PKCS#1 v1.5 簽名。
  4. Nonce + Timestamp:防重放攻擊;接收端需儲存近期使用過的 Nonce(Redis Set + TTL)。
  5. 金鑰輪換:定期更換 RSA 金鑰對,支援版本號(v)平滑遷移。
  6. 錯誤訊息不洩露細節:對外統一回傳 "Invalid request",詳細錯誤僅記錄日誌。

常見坑點

  • ❌ 直接用 RSA 加密大量資料(RSA 只能加密 位元組)
  • ❌ 使用 ECB 模式(無 IV、模式可見)
  • ❌ 固定 IV 或重複使用 AES Key
  • ❌ 自行實作加密演算法(請用經審計的庫)
  • ❌ 忽略時間戳/Nonce 驗證(重放攻擊)
  • ❌ 私鑰洩露(Git、日誌、備份、容器映像)

掌握 AES/RSA 混合加密與簽名驗證,是構建安全 API 介面的核心技能。phpseclib 純 PHP 實現、零擴展依賴、符合現代密碼學最佳實踐,是 PHP 專案的首選。

copyright © 萬盛學電腦網 all rights reserved