萬盛學電腦網

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

PHP RSA 非對稱加密完整實作:OpenSSL 擴展簽名、驗簽、加密、解密與填充模式詳解

前言

RSA 非對稱加密是資料傳輸安全、API 簽名驗證、數位憑證的核心技術。PHP openssl 擴展提供完整 RSA 操作介面。本文封裝生產級 RSA 類,支援多種編碼格式、填充模式、金鑰格式,並詳細解析填充模式選擇、資料長度限制、跨語言互操作關鍵點。

核心概念速覽

概念說明關鍵點
公鑰加密、驗簽可公開傳播,X.509 PEM 格式 (-----BEGIN PUBLIC KEY-----)
私鑰解密、簽名嚴格保密,PKCS#1/PKCS#8 PEM 格式 (-----BEGIN PRIVATE KEY-----)
填充模式資料填充至金鑰長度區塊加密必須用 PKCS1_OAEP (推薦) 或 PKCS1_v1.5,解密須匹配
區塊大小等於金鑰位元組數1024-bit key = 128 bytes;最大明文 = key_bytes - padding_overhead
簽名演算法SHA256withRSA (推薦)PHP openssl_sign() 預設 SHA1,必須指定 'sha256WithRSAEncryption'

資料長度限制計算

金鑰長度區塊大小PKCS#1 v1.5 最大明文OAEP (SHA-256) 最大明文簽名輸出
1024-bit128 bytes117 bytes86 bytes128 bytes
2048-bit256 bytes245 bytes190 bytes256 bytes
4096-bit512 bytes501 bytes446 bytes512 bytes

超長資料加密策略:混合加密 —— AES-256-GCM 加密資料 + RSA 加密 AES 金鑰。

生產級 RSA 類完整實作

<?php
declare(strict_types=1);

namespace App\Security;

use OpenSSLAsymmetricKey;

class RSA
{
    public const ENCODING_BASE64 = 'base64';
    public const ENCODING_HEX = 'hex';
    public const ENCODING_BINARY = 'binary';

    public const PADDING_PKCS1 = OPENSSL_PKCS1_PADDING;
    public const PADDING_OAEP_SHA256 = OPENSSL_OAEP_PADDING; // PHP 8.1+ 需指定 digest
    public const PADDING_NONE = OPENSSL_NO_PADDING;

    private ?OpenSSLAsymmetricKey $publicKey = null;
    private ?OpenSSLAsymmetricKey $privateKey = null;
    private string $defaultEncoding = self::ENCODING_BASE64;
    private int $defaultPadding = self::PADDING_PKCS1;

    public function __construct(
        string $publicKeyPath = '',
        string $privateKeyPath = '',
        string $privateKeyPassphrase = ''
    ) {
        if ($publicKeyPath) $this->loadPublicKey($publicKeyPath);
        if ($privateKeyPath) $this->loadPrivateKey($privateKeyPath, $privateKeyPassphrase);
    }

    // === 金鑰載入 ===
    public function loadPublicKey(string $pathOrContent): bool
    {
        $key = $this->loadKey($pathOrContent, true);
        if (!$key) return false;
        $this->publicKey = $key;
        return true;
    }

    public function loadPrivateKey(string $pathOrContent, string $passphrase = ''): bool
    {
        $key = $this->loadKey($pathOrContent, false, $passphrase);
        if (!$key) return false;
        $this->privateKey = $key;
        return true;
    }

    private function loadKey(string $pathOrContent, bool $isPublic, string $passphrase = ''): ?OpenSSLAsymmetricKey
    {
        $content = file_exists($pathOrContent) ? file_get_contents($pathOrContent) : $pathOrContent;
        if ($content === false) return null;

        $options = $passphrase ? ['passphrase' => $passphrase] : [];
        $key = $isPublic 
            ? openssl_pkey_get_public($content)
            : openssl_pkey_get_private($content, $passphrase);
            
        if (!$key) {
            $err = openssl_error_string();
            throw new \RuntimeException("載入金鑰失敗: {$err}");
        }
        return $key;
    }

    // === 簽名/驗簽 (推薦 SHA256) ===
    public function sign(string $data, string $algo = 'sha256WithRSAEncryption', string $encoding = ''): string|false
    {
        if (!$this->privateKey) throw new \LogicException('私鑰未載入');
        
        $signature = '';
        $ok = openssl_sign($data, $signature, $this->privateKey, $algo);
        if (!$ok) return false;
        
        return $this->encode($signature, $encoding ?: $this->defaultEncoding);
    }

    public function verify(string $data, string $signature, string $algo = 'sha256WithRSAEncryption', string $encoding = ''): bool
    {
        if (!$this->publicKey) throw new \LogicException('公鑰未載入');
        
        $sig = $this->decode($signature, $encoding ?: $this->defaultEncoding);
        if ($sig === false) return false;
        
        $result = openssl_verify($data, $sig, $this->publicKey, $algo);
        return $result === 1; // 1=成功, 0=失敗, -1=錯誤
    }

    // === 加密/解密 ===
    public function encrypt(string $data, int $padding = -1, string $encoding = ''): string|false
    {
        if (!$this->publicKey) throw new \LogicException('公鑰未載入');
        $padding = $padding >= 0 ? $padding : $this->defaultPadding;
        
        // 檢查資料長度
        $keyDetails = openssl_pkey_get_details($this->publicKey);
        $maxLen = $this->getMaxEncryptLen($keyDetails['bits'], $padding);
        if (strlen($data) > $maxLen) {
            throw new \LengthException("資料過長: " . strlen($data) . " > {$maxLen} bytes (建議使用混合加密)");
        }

        $encrypted = '';
        $ok = openssl_public_encrypt($data, $encrypted, $this->publicKey, $padding);
        if (!$ok) return false;
        
        return $this->encode($encrypted, $encoding ?: $this->defaultEncoding);
    }

    public function decrypt(string $data, int $padding = -1, string $encoding = '', bool $reverseBytes = false): string|false
    {
        if (!$this->privateKey) throw new \LogicException('私鑰未載入');
        $padding = $padding >= 0 ? $padding : $this->defaultPadding;
        
        $decoded = $this->decode($data, $encoding ?: $this->defaultEncoding);
        if ($decoded === false) return false;

        if ($reverseBytes) {
            $decoded = strrev($decoded); // 相容 Microsoft CryptoAPI
        }

        $decrypted = '';
        $ok = openssl_private_decrypt($decoded, $decrypted, $this->privateKey, $padding);
        if (!$ok) return false;
        
        return $decrypted;
    }

    // === 工具方法 ===
    private function getMaxEncryptLen(int $keyBits, int $padding): int
    {
        $keyBytes = $keyBits >> 3;
        return match ($padding) {
            self::PADDING_PKCS1 => $keyBytes - 11,
            self::PADDING_OAEP_SHA256 => $keyBytes - 2 - 2 * 32, // 2*hash_len + 2
            self::PADDING_NONE => $keyBytes,
            default => $keyBytes - 11,
        };
    }

    private function encode(string $binary, string $encoding): string
    {
        return match ($encoding) {
            self::ENCODING_BASE64 => base64_encode($binary),
            self::ENCODING_HEX => bin2hex($binary),
            self::ENCODING_BINARY => $binary,
            default => throw new \InvalidArgumentException("未知編碼: {$encoding}"),
        };
    }

    private function decode(string $encoded, string $encoding): string|false
    {
        return match ($encoding) {
            self::ENCODING_BASE64 => base64_decode($encoded, true),
            self::ENCODING_HEX => hex2bin($encoded),
            self::ENCODING_BINARY => $encoded,
            default => false,
        };
    }

    // === 靜態工廠方法 ===
    public static function fromPemStrings(string $publicPem, string $privatePem = '', string $passphrase = ''): self
    {
        $rsa = new self();
        $rsa->loadPublicKey($publicPem);
        if ($privatePem) $rsa->loadPrivateKey($privatePem, $passphrase);
        return $rsa;
    }
}
?>

使用範例

<?php
require_once 'RSA.php';

$rsa = new RSA(
    __DIR__ . '/keys/public.pem',
    __DIR__ . '/keys/private.pem',
    'keypassphrase' // 私鑰密碼 (如有)
);

// 1. 簽名驗簽
$data = '重要業務資料: 訂單編號 20240115001';
$signature = $rsa->sign($data, 'sha256WithRSAEncryption', RSA::ENCODING_BASE64);
echo "簽名: {$signature}\n";

$valid = $rsa->verify($data, $signature, 'sha256WithRSAEncryption', RSA::ENCODING_BASE64);
echo "驗證: " . ($valid ? '通過' : '失敗') . "\n";

// 2. 加密解密 (短資料)
$secret = 'AES-256-GCM 金鑰: ' . bin2hex(random_bytes(32));
$encrypted = $rsa->encrypt($secret, RSA::PADDING_PKCS1, RSA::ENCODING_BASE64);
echo "加密: {$encrypted}\n";

$decrypted = $rsa->decrypt($encrypted, RSA::PADDING_PKCS1, RSA::ENCODING_BASE64);
echo "解密: {$decrypted}\n";
echo "匹配: " . ($secret === $decrypted ? '是' : '否') . "\n";

// 3. 跨語言互操作要點
// Java: Cipher.getInstance("RSA/ECB/PKCS1Padding") / "RSA/ECB/OAEPWithSHA-256AndMGF1Padding"
// Python: Crypto.Cipher.PKCS1_v1_5 / PKCS1_OAEP
// Node: crypto.publicEncrypt({key, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING}, buffer)
?>

金鑰生成指令 (OpenSSL CLI)

# 生成 2048-bit 私鑰 (PKCS#8 格式,推薦)
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out private.pem

# 導出公鑰
openssl pkey -in private.pem -pubout -out public.pem

# 加密私鑰 (AES-256)
openssl pkey -in private.pem -aes256 -out private_enc.pem -passout pass:yourpass

# 檢視金鑰資訊
openssl pkey -in private.pem -text -noout
openssl pkey -in public.pem -pubin -text -noout

常見坑點與解決

問題原因解決
openssl_error_string() 返回 "error:0406D06C:rsa routines:RSA_padding_check_PKCS1_type_2:data greater than mod len"明文超過最大長度檢查資料長度,改用混合加密 (AES+RSA)
驗簽失敗但資料正確簽名演算法不匹配 (SHA1 vs SHA256)雙端統一指定 sha256WithRSAEncryption
解密失敗 "data too large for key size"加密端用 OAEP,解密端用 PKCS1雙端填充模式必須一致
跨語言解密失敗位元組序不同 (Big-endian vs Little-endian).NET/CryptoAPI 需 $reverseBytes=true;Java/Node/Python 通常不需
PHP 8.1+ OAEP 需指定 digestAPI 變更使用 openssl_encrypt() 而非 openssl_public_encrypt() 以支援 OAEP 參數

混合加密實作 (大資料加密標準做法)

<?php
function hybridEncrypt(string $data, RSA $rsa): array
{
    // 1. 生成隨機 AES-256-GCM 金鑰
    $aesKey = random_bytes(32);
    $iv = random_bytes(12); // GCM 建議 12 bytes IV
    
    // 2. AES 加密資料
    $ciphertext = openssl_encrypt($data, 'aes-256-gcm', $aesKey, OPENSSL_RAW_DATA, $iv, $tag);
    if ($ciphertext === false) throw new \RuntimeException('AES 加密失敗');
    
    // 3. RSA 加密 AES 金鑰
    $encryptedKey = $rsa->encrypt($aesKey, RSA::PADDING_OAEP_SHA256, RSA::ENCODING_BASE64);
    if ($encryptedKey === false) throw new \RuntimeException('RSA 加密金鑰失敗');
    
    return [
        'encrypted_key' => $encryptedKey,
        'iv' => base64_encode($iv),
        'tag' => base64_encode($tag),
        'ciphertext' => base64_encode($ciphertext),
        'algorithm' => 'AES-256-GCM + RSA-OAEP-SHA256',
    ];
}

function hybridDecrypt(array $package, RSA $rsa): string
{
    $aesKey = $rsa->decrypt($package['encrypted_key'], RSA::PADDING_OAEP_SHA256, RSA::ENCODING_BASE64);
    if ($aesKey === false) throw new \RuntimeException('RSA 解密金鑰失敗');
    
    $plaintext = openssl_decrypt(
        base64_decode($package['ciphertext']),
        'aes-256-gcm',
        $aesKey,
        OPENSSL_RAW_DATA,
        base64_decode($package['iv']),
        base64_decode($package['tag'])
    );
    if ($plaintext === false) throw new \RuntimeException('AES 解密失敗');
    
    return $plaintext;
}
?>

總結

PHP RSA 操作核心要點:

  1. 金鑰格式:PEM 格式,PKCS#8 私鑰、X.509 公鑰
  2. 填充模式:加密推薦 OAEP-SHA256,兼容舊系統用 PKCS#1 v1.5
  3. 簽名演算法:必須指定 SHA256,勿用預設 SHA1
  4. 資料長度:受限於金鑰大小,大資料必須用混合加密
  5. 跨語言:注意位元組序、填充模式、編碼格式一致性

本文 RSA 類封裝了完整生命週期管理、多編碼支援、長度檢查、錯誤處理,可直接納入專案安全庫。

copyright © 萬盛學電腦網 all rights reserved