萬盛學電腦網

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

PHP OpenSSL 實戰:RSA 非對稱加密、簽名驗證與憑證生成完整指南

前置需求

  • PHP 安裝 openssl 擴充模組(php -m | grep openssl)
  • OpenSSL 庫版本 ≥ 1.1.1(支援 TLS 1.3、更佳效能)
  • 理解公開金鑰加密、私鑰解密;私鑰簽名、公開金鑰驗證的基本原理

一、金鑰對生成(PEM 格式)

<?php
/**
 * 生成 RSA 金鑰對並儲存為 PEM 檔案
 * @param int $bits 金鑰長度:2048(最低推薦)、4096(高安全)
 * @return array ['private_key' => string, 'public_key' => string]
 */
function generateRsaKeyPair(int $bits = 4096): array
{
    $config = [
        'digest_alg'       => 'sha512',
        'private_key_bits' => $bits,
        'private_key_type' => OPENSSL_KEYTYPE_RSA,
    ];
    
    $res = openssl_pkey_new($config);
    if (!$res) throw new RuntimeException('金鑰生成失敗: ' . openssl_error_string());
    
    // 匯出私鑰(PKCS#8 格式,含 -----BEGIN PRIVATE KEY-----)
    openssl_pkey_export($res, $privateKey);
    
    // 取得公開金鑰資訊
    $details = openssl_pkey_get_details($res);
    $publicKey = $details['key']; // -----BEGIN PUBLIC KEY-----
    
    openssl_free_key($res);
    
    return [
        'private_key' => $privateKey,
        'public_key'  => $publicKey,
    ];
}

// 使用範例
$keys = generateRsaKeyPair(4096);
file_put_contents('storage/keys/private.pem', $keys['private_key']);
file_put_contents('storage/keys/public.pem',  $keys['public_key']);
// 實際專案建議:私鑰存放於不可公開目錄,權限 0600
?>

二、加密與解密(資料長度限制)

重要限制:RSA 直接加密資料長度 不能超過金鑰長度 - padding 開銷。
2048-bit 金鑰 + PKCS#1 v1.5 padding → 最大加密 245 位元組。
4096-bit 金鑰 → 最大加密 501 位元組。
實務上:採用混合加密(Hybrid Encryption)——用 AES-256-GCM 加密資料,再用 RSA 加密 AES 金鑰。

直接加密/解密(僅適用極短資料,如 AES Key、JWT 簽名)

<?php
function rsaEncrypt(string $data, string $publicKeyPem): string|false
{
    $pubKey = openssl_pkey_get_public($publicKeyPem);
    if (!$pubKey) return false;
    
    $encrypted = '';
    $ok = openssl_public_encrypt($data, $encrypted, $pubKey, OPENSSL_PKCS1_PADDING);
    openssl_free_key($pubKey);
    return $ok ? base64_encode($encrypted) : false;
}

function rsaDecrypt(string $base64Encrypted, string $privateKeyPem): string|false
{
    $privKey = openssl_pkey_get_private($privateKeyPem);
    if (!$privKey) return false;
    
    $decrypted = '';
    $ok = openssl_private_decrypt(base64_decode($base64Encrypted), $decrypted, $privKey, OPENSSL_PKCS1_PADDING);
    openssl_free_key($privKey);
    return $ok ? $decrypted : false;
}
?>

三、數位簽名與驗證(防篡改、身分認證)

<?php
/**
 * 私鑰簽名(RSA + SHA256)
 */
function rsaSign(string $data, string $privateKeyPem, string $algo = 'sha256'): string|false
{
    $privKey = openssl_pkey_get_private($privateKeyPem);
    if (!$privKey) return false;
    
    $signature = '';
    $ok = openssl_sign($data, $signature, $privKey, $algo);
    openssl_free_key($privKey);
    return $ok ? base64_encode($signature) : false;
}

/**
 * 公開金鑰驗證簽名
 */
function rsaVerify(string $data, string $base64Signature, string $publicKeyPem, string $algo = 'sha256'): bool
{
    $pubKey = openssl_pkey_get_public($publicKeyPem);
    if (!$pubKey) return false;
    
    $ok = openssl_verify($data, base64_decode($base64Signature), $pubKey, $algo);
    openssl_free_key($pubKey);
    return $ok === 1; // 1=成功, 0=失敗, -1=錯誤
}
?>

四、混合加密實戰封裝(適用任意長度資料)

<?php
class HybridCrypto
{
    private const AES_ALGO = 'aes-256-gcm';
    private const KEY_BYTES = 32; // 256 bits
    private const IV_BYTES = 12;  // GCM 建議 96-bit IV
    private const TAG_BYTES = 16; // 128-bit 標籤
    
    /**
     * 加密:隨機 AES Key + IV -> 加密資料 -> RSA 加密 AES Key -> 組合輸出
     * 返回格式:base64( encrypted_aes_key . iv . ciphertext . tag )
     */
    public static function encrypt(string $data, string $publicKeyPem): string|false
    {
        $aesKey = random_bytes(self::KEY_BYTES);
        $iv     = random_bytes(self::IV_BYTES);
        
        $ciphertext = openssl_encrypt($data, self::AES_ALGO, $aesKey, OPENSSL_RAW_DATA, $iv, $tag);
        if ($ciphertext === false) return false;
        
        $pubKey = openssl_pkey_get_public($publicKeyPem);
        if (!$pubKey) return false;
        
        $encryptedKey = '';
        $ok = openssl_public_encrypt($aesKey, $encryptedKey, $pubKey, OPENSSL_PKCS1_OAEP_PADDING); // OAEP 更安全
        openssl_free_key($pubKey);
        if (!$ok) return false;
        
        // 組合:encKeyLen(2 bytes) + encKey + iv + ciphertext + tag
        $encKeyLen = pack('n', strlen($encryptedKey));
        return base64_encode($encKeyLen . $encryptedKey . $iv . $ciphertext . $tag);
    }
    
    /**
     * 解密:Base64 解碼 -> 拆分 -> RSA 解密 AES Key -> AES 解密資料
     */
    public static function decrypt(string $base64Payload, string $privateKeyPem): string|false
    {
        $payload = base64_decode($base64Payload, true);
        if ($payload === false) return false;
        
        // 解析結構
        $encKeyLen = unpack('n', substr($payload, 0, 2))[1];
        $offset = 2;
        $encryptedKey = substr($payload, $offset, $encKeyLen); $offset += $encKeyLen;
        $iv           = substr($payload, $offset, self::IV_BYTES); $offset += self::IV_BYTES;
        $tag          = substr($payload, -self::TAG_BYTES);
        $ciphertext   = substr($payload, $offset, -self::TAG_BYTES);
        
        // RSA 解密 AES Key
        $privKey = openssl_pkey_get_private($privateKeyPem);
        if (!$privKey) return false;
        $aesKey = '';
        $ok = openssl_private_decrypt($encryptedKey, $aesKey, $privKey, OPENSSL_PKCS1_OAEP_PADDING);
        openssl_free_key($privKey);
        if (!$ok) return false;
        
        // AES 解密
        return openssl_decrypt($ciphertext, self::AES_ALGO, $aesKey, OPENSSL_RAW_DATA, $iv, $tag);
    }
}

// 使用範例
$keys = generateRsaKeyPair();
$plaintext = '這是一段包含中文的長文本,可以是 JSON、XML 或任意二進位資料...';
$encrypted = HybridCrypto::encrypt($plaintext, $keys['public_key']);
$decrypted = HybridCrypto::decrypt($encrypted, $keys['private_key']);
var_dump($plaintext === $decrypted); // true
?>

五、X.509 憑證(CSR 生成、自簽憑證)

<?php
function generateSelfSignedCert(array $dn, string $privateKeyPem, int $days = 365): string|false
{
    $privKey = openssl_pkey_get_private($privateKeyPem);
    if (!$privKey) return false;
    
    $csr = openssl_csr_new($dn, $privKey, ['digest_alg' => 'sha256']);
    if (!$csr) return false;
    
    $cert = openssl_csr_sign($csr, null, $privKey, $days, ['digest_alg' => 'sha256']);
    openssl_csr_free($csr);
    openssl_free_key($privKey);
    
    if (!$cert) return false;
    
    openssl_x509_export($cert, $certPem);
    openssl_x509_free($cert);
    return $certPem;
}

// 使用
$dn = [
    'countryName'            => 'TW',
    'stateOrProvinceName'    => 'Taipei',
    'localityName'           => 'Taipei',
    'organizationName'       => 'My Company',
    'organizationalUnitName' => 'IT Dept',
    'commonName'             => 'api.mycompany.com',
    'emailAddress'           => 'admin@mycompany.com',
];
$certPem = generateSelfSignedCert($dn, $keys['private_key'], 3650); // 10 年
?>

六、常見錯誤與除錯技巧

  1. openssl_error_string():每次失敗後呼叫,獲取詳細錯誤訊息。
  2. 金鑰格式不符:確認 PEM 內容包含正確的 -----BEGIN ...----- 標頭,無多餘空白行。
  3. Padding 模式不一致:加密用 OPENSSL_PKCS1_OAEP_PADDING,解密必須同模式;舊系統可能用 OPENSSL_PKCS1_PADDING(PKCS#1 v1.5)。
  4. 資料過長:直接 RSA 加密超過長度限制會返回 false,改用混合加密。
  5. 私鑰加密儲存:生產環境私鑰應以 AES 加密儲存(openssl_pkey_export 可指定密語),載入時提供密語。

結語

OpenSSL 是 PHP 進行非對稱加密、簽名驗證、憑證管理的核心工具。掌握「混合加密」架構、正確選擇 Padding 模式、妥善管理金鑰生命週期,是建構安全系統(API 簽名驗證、資料加密傳輸、JWT 簽名、mTLS)的基石。建議將上述封裝類納入專案共用庫,統一錯誤處理與日誌記錄。

copyright © 萬盛學電腦網 all rights reserved