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
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 字節)。長資料需採用混合加密:
RSA加密的AES金鑰 + AES加密的資料。| 環境 | 問題 | 解決 |
|---|---|---|
| Windows | 缺少 libeay32.dll、ssleay32.dll | 複製至 System32 或 PHP 目錄 |
| Windows | php_openssl.dll 未啟用 | php.ini 取消註釋 extension=openssl |
| Linux | 未安裝 openssl-devel | yum install openssl-devel / apt install libssl-dev 重編譯 PHP |
| 所有 | 金鑰格式不匹配 | 統一使用 PKCS#8 PEM 格式,檢查 -----BEGIN PRIVATE KEY----- |
chmod 600,嚴禁提交版本庫。OPENSSL_ALGO_SHA256,避免預設 SHA1。