傳統流程需 `openssl pkcs12 -in key.pfx -out key.pem -nodes` 轉檔,再載入 PEM。PHP `openssl_pkcs12_read()` 可直接解析 PFX 取得私鑰資源,簡化部署、避免明文私鑰落地。
<?php
/**
* 以 PFX 憑證對資料簽名
*
* @param string $strData 待簽原文
* @param string $pfxPath PFX 檔路徑
* @param string $pfxPassword PFX 密碼 (空字串為無密碼)
* @param int $algo 簽名演算法 (預設 OPENSSL_ALGO_SHA1)
* @return string|false 成功回傳 hex 簽名,失敗回傳 false
*/
function signWithPfx(string $strData, string $pfxPath, string $pfxPassword = '', int $algo = OPENSSL_ALGO_SHA1): string|false
{
if (!file_exists($pfxPath)) {
error_log("signWithPfx: PFX 不存在 $pfxPath");
return false;
}
$pkcs12 = file_get_contents($pfxPath);
$certs = [];
if (!openssl_pkcs12_read($pkcs12, $certs, $pfxPassword)) {
error_log("signWithPfx: PFX 解析失敗 - " . openssl_error_string());
return false;
}
$privateKey = $certs['pkey'] ?? null;
if (!$privateKey) {
error_log("signWithPfx: PFX 中無私鑰");
return false;
}
$signedMsg = '';
if (!openssl_sign($strData, $signedMsg, $privateKey, $algo)) {
error_log("signWithPfx: 簽名失敗 - " . openssl_error_string());
return false;
}
// 釋放私鑰資源 (重要,避免記憶體洩漏)
openssl_free_key($privateKey);
return bin2hex($signedMsg);
}
| 常數 | 演算法 | 適用場景 |
|---|---|---|
OPENSSL_ALGO_SHA1 | SHA-1 | 舊系統相容、DSA 強制 |
OPENSSL_ALGO_DSS1 | DSS1 (SHA-1) | DSA 金鑰專用 |
OPENSSL_ALGO_SHA256 | SHA-256 | 現代標準推薦 (RSA/ECDSA) |
OPENSSL_ALGO_SHA384 | SHA-384 | 高安全需求 |
OPENSSL_ALGO_SHA512 | SHA-512 | 最高安全需求 |
OPENSSL_ALGO_RMD160 | RIPEMD-160 | 特定標準 (如歐洲) |
<?php
$data = '{"order_id":12345,"amount":99.9,"timestamp":1699999999}';
// RSA-SHA256 (推薦)
$sig = signWithPfx($data, 'merchant.pfx', 'pfx_password', OPENSSL_ALGO_SHA256);
if ($sig) {
echo "簽名(hex): $sig\n";
// 送往支付網關...
} else {
echo "簽名失敗\n";
}
$certs = [];
openssl_pkcs12_read($pkcs12, $certs, $password);
$publicKeyPem = $certs['cert']; // PEM 格式公鑰/憑證
file_put_contents('public.pem', $publicKeyPem); // 提供給合作夥伴
`openssl_pkcs12_read()` + `openssl_sign()` 形成「PFX 直簽」最短路徑,配合演算法參數化,滿足新舊系統共存需求。建議封裝為 Service 類別,統一管理金鑰載入、快取、日誌與例外處理。