萬盛學電腦網

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

PHP RSA 非對稱加密完整實戰:金鑰生成、加解密、OpenSSL 擴展配置

前言

RSA 非對稱加密廣泛用於 API 簽名、敏感資料傳輸、登入加密。本文涵蓋 OpenSSL 生成金鑰對、PHP 實作公私鑰加解密、Base64 安全傳輸、常見坑點與擴展配置。

金鑰生成

# 1. 生成原始私鑰 (PKCS#1)
openssl genrsa -out rsa_private_key.pem 2048

# 2. 轉換為 PKCS#8 格式 (推薦,跨語言相容性佳)
openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt -out private_key.pem

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

關鍵點:私鑰(PKCS#8)放伺服器端,公鑰分發給客戶端。私鑰加密 → 公鑰解密(簽名驗證);公鑰加密 → 私鑰解密(資料機密)。

PHP 加解密實作

<?php
class RsaCrypto {
    private $privateKey;
    private $publicKey;
    private $piKey;  // 資源句柄
    private $puKey;

    public function __construct($privateKeyPath, $publicKeyPath) {
        $this->privateKey = file_get_contents($privateKeyPath);
        $this->publicKey  = file_get_contents($publicKeyPath);

        $this->piKey = openssl_pkey_get_private($this->privateKey);
        $this->puKey = openssl_pkey_get_public($this->publicKey);

        if (!$this->piKey || !$this->puKey) {
            throw new Exception('金鑰載入失敗,請檢查路徑與格式');
        }
    }

    /** 私鑰加密 → 公鑰解密(簽名場景) */
    public function privateEncrypt($data) {
        openssl_private_encrypt($data, $encrypted, $this->piKey);
        return base64_encode($encrypted);
    }

    public function publicDecrypt($encrypted) {
        openssl_public_decrypt(base64_decode($encrypted), $decrypted, $this->puKey);
        return $decrypted;
    }

    /** 公鑰加密 → 私鑰解密(機密傳輸) */
    public function publicEncrypt($data) {
        openssl_public_encrypt($data, $encrypted, $this->puKey);
        return base64_encode($encrypted);
    }

    public function privateDecrypt($encrypted) {
        openssl_private_decrypt(base64_decode($encrypted), $decrypted, $this->piKey);
        return $decrypted;
    }

    /** 簽名與驗簽(推薦使用 SHA256) */
    public function sign($data) {
        openssl_sign($data, $signature, $this->piKey, OPENSSL_ALGO_SHA256);
        return base64_encode($signature);
    }

    public function verify($data, $signature) {
        return openssl_verify($data, base64_decode($signature), $this->puKey, OPENSSL_ALGO_SHA256) === 1;
    }

    public function __destruct() {
        if ($this->piKey) openssl_free_key($this->piKey);
        if ($this->puKey) openssl_free_key($this->puKey);
    }
}

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

$data = 'php rsa encryption test';

// 1. 公鑰加密,私鑰解密
$encrypted = $rsa->publicEncrypt($data);
$decrypted = $rsa->privateDecrypt($encrypted);
echo "公鑰加密/私鑰解密: $decrypted\n";

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

關鍵限制與分段處理

RSA 加密資料長度受限於金鑰長度(2048 bit 金鑰最大加密 245 字節)。長資料需採用混合加密:

  1. 生成隨機 AES-256 金鑰加密資料。
  2. 用 RSA 公鑰加密 AES 金鑰。
  3. 傳輸:RSA加密的AES金鑰 + AES加密的資料。

OpenSSL 擴展配置排坑

環境問題解決
Windows缺少 libeay32.dll、ssleay32.dll複製至 System32 或 PHP 目錄
Windowsphp_openssl.dll 未啟用php.ini 取消註釋 extension=openssl
Linux未安裝 openssl-develyum install openssl-devel / apt install libssl-dev 重編譯 PHP
所有金鑰格式不匹配統一使用 PKCS#8 PEM 格式,檢查 -----BEGIN PRIVATE KEY-----

安全最佳實踐

  • 私鑰檔案權限 chmod 600,嚴禁提交版本庫。
  • 生產環境使用 HSM 或 KMS 管理金鑰,勿明文存檔。
  • 定期輪換金鑰,建立撤銷機制。
  • 簽名演算法指定 OPENSSL_ALGO_SHA256,避免預設 SHA1。
copyright © 萬盛學電腦網 all rights reserved