class RsaKeyManager {
private string $keyDir;
private const PRIV_FILE = 'private_key.pem';
private const PUB_FILE = 'public_key.pem';
private const KEY_BITS = 2048; // 建議 ≥ 2048,高安全性 4096
public function __construct(string $keyDir) {
$this->keyDir = rtrim($keyDir, '/');
if (!is_dir($this->keyDir)) {
mkdir($this->keyDir, 0700, true); // 僅擁有者可讀寫
}
}
public function generateKeys(): bool {
$config = [
'private_key_bits' => self::KEY_BITS,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
];
$res = openssl_pkey_new($config);
if (!$res) return false;
// 匯出私鑰(PKCS#8 格式,無加密)
openssl_pkey_export($res, $privKeyPem);
file_put_contents($this->keyDir . '/' . self::PRIV_FILE, $privKeyPem, LOCK_EX);
chmod($this->keyDir . '/' . self::PRIV_FILE, 0600);
// 取得公鑰
$pubKeyDetail = openssl_pkey_get_details($res);
$pubKeyPem = $pubKeyDetail['key'];
file_put_contents($this->keyDir . '/' . self::PUB_FILE, $pubKeyPem, LOCK_EX);
chmod($this->keyDir . '/' . self::PUB_FILE, 0644);
openssl_free_key($res);
return true;
}
public function getPrivateKey(): string|false {
$path = $this->keyDir . '/' . self::PRIV_FILE;
return file_exists($path) ? file_get_contents($path) : false;
}
public function getPublicKey(): string|false {
$path = $this->keyDir . '/' . self::PUB_FILE;
return file_exists($path) ? file_get_contents($path) : false;
}
}
class RsaCryptor {
private $privKeyRes;
private $pubKeyRes;
public function __construct(string $privKeyPem = '', string $pubKeyPem = '') {
if ($privKeyPem) $this->privKeyRes = openssl_pkey_get_private($privKeyPem);
if ($pubKeyPem) $this->pubKeyRes = openssl_pkey_get_public($pubKeyPem);
}
public function __destruct() {
if ($this->privKeyRes) openssl_free_key($this->privKeyRes);
if ($this->pubKeyRes) openssl_free_key($this->pubKeyRes);
}
// 公鑰加密(資料長度 < 金鑰長度/8 - 42 bytes for OAEP)
public function publicEncrypt(string $data): string|false {
if (!$this->pubKeyRes) return false;
$ok = openssl_public_encrypt($data, $encrypted, $this->pubKeyRes, OPENSSL_PKCS1_OAEP_PADDING);
return $ok ? base64_encode($encrypted) : false;
}
// 私鑰解密
public function privateDecrypt(string $base64Data): string|false {
if (!$this->privKeyRes) return false;
$data = base64_decode($base64Data, true);
if ($data === false) return false;
$ok = openssl_private_decrypt($data, $decrypted, $this->privKeyRes, OPENSSL_PKCS1_OAEP_PADDING);
return $ok ? $decrypted : false;
}
// 私鑰加密(簽名用途,非機密傳輸)
public function privateEncrypt(string $data): string|false {
if (!$this->privKeyRes) return false;
$ok = openssl_private_encrypt($data, $encrypted, $this->privKeyRes, OPENSSL_PKCS1_PADDING);
return $ok ? base64_encode($encrypted) : false;
}
// 公鑰解密(驗證簽名用途)
public function publicDecrypt(string $base64Data): string|false {
if (!$this->pubKeyRes) return false;
$data = base64_decode($base64Data, true);
if ($data === false) return false;
$ok = openssl_public_decrypt($data, $decrypted, $this->pubKeyRes, OPENSSL_PKCS1_PADDING);
return $ok ? $decrypted : false;
}
}
class RsaSigner {
private $privKeyRes;
private $pubKeyRes;
private const ALGO = OPENSSL_ALGO_SHA256; // 或 SHA512
public function __construct(string $privKeyPem = '', string $pubKeyPem = '') {
if ($privKeyPem) $this->privKeyRes = openssl_pkey_get_private($privKeyPem);
if ($pubKeyPem) $this->pubKeyRes = openssl_pkey_get_public($pubKeyPem);
}
public function sign(string $data): string|false {
if (!$this->privKeyRes) return false;
$ok = openssl_sign($data, $signature, $this->privKeyRes, self::ALGO);
return $ok ? base64_encode($signature) : false;
}
public function verify(string $data, string $base64Signature): bool {
if (!$this->pubKeyRes) return false;
$signature = base64_decode($base64Signature, true);
if ($signature === false) return false;
$result = openssl_verify($data, $signature, $this->pubKeyRes, self::ALGO);
return $result === 1;
}
}
// 1. 生成金鑰對(僅需一次)
$km = new RsaKeyManager(__DIR__ . '/keys');
$km->generateKeys();
$privKey = $km->getPrivateKey();
$pubKey = $km->getPublicKey();
// 2. 加密傳輸
$cryptor = new RsaCryptor($privKey, $pubKey);
$secret = '敏感資料:身分證字號 A123456789';
$encrypted = $cryptor->publicEncrypt($secret);
echo "加密後:" . $encrypted . "\n";
$decrypted = $cryptor->privateDecrypt($encrypted);
echo "解密後:" . $decrypted . "\n";
// 3. 簽名驗證
$signer = new RsaSigner($privKey, $pubKey);
$payload = json_encode(['user_id' => 1001, 'action' => 'withdraw', 'amount' => 5000, 'timestamp' => time()]);
$signature = $signer->sign($payload);
echo "簽名:" . $signature . "\n";
$valid = $signer->verify($payload, $signature);
echo "驗證:" . ($valid ? '通過' : '失敗') . "\n";
OPENSSL_PKCS1_OAEP_PADDING,防止 Padding Oracle 攻擊。簽名用 OPENSSL_PKCS1_PADDING (PKCS#1 v1.5) 或 PSS。function hybridEncrypt(string $data, string $pubKeyPem): array|false {
// 1. 生成隨機 AES-256 金鑰 + IV
$aesKey = random_bytes(32);
$iv = random_bytes(16);
// 2. AES-GCM 加密資料
$ciphertext = openssl_encrypt($data, 'aes-256-gcm', $aesKey, OPENSSL_RAW_DATA, $iv, $tag);
if ($ciphertext === false) return false;
// 3. RSA-OAEP 加密 AES 金鑰
$cryptor = new RsaCryptor('', $pubKeyPem);
$encryptedKey = $cryptor->publicEncrypt($aesKey);
if (!$encryptedKey) return false;
return [
'key' => $encryptedKey, // RSA 加密的 AES 金鑰
'iv' => base64_encode($iv),
'tag' => base64_encode($tag),
'data' => base64_encode($ciphertext),
];
}
function hybridDecrypt(array $package, string $privKeyPem): string|false {
// 1. RSA 解密 AES 金鑰
$cryptor = new RsaCryptor($privKeyPem, '');
$aesKey = $cryptor->privateDecrypt($package['key']);
if (!$aesKey) return false;
// 2. AES-GCM 解密資料
$data = openssl_decrypt(
base64_decode($package['data']),
'aes-256-gcm',
$aesKey,
OPENSSL_RAW_DATA,
base64_decode($package['iv']),
base64_decode($package['tag'])
);
return $data !== false ? $data : false;
}
OpenSSL 提供完整的 RSA 非對稱加密、簽名驗證功能。正確選擇 Padding 模式、妥善管理金鑰生命週期、採用混合加密處理大資料,是構建安全加密系統的關鍵要素。