萬盛學電腦網

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

PHP PKI 加密技術 (OpenSSL) 詳解:金鑰生成、加解密、簽名驗證

OpenSSL 擴展啟用

php.ini 啟用:extension=openssl (Windows: extension=php_openssl.dll),重啟服務。

核心概念

  • 公鑰加密,私鑰解密:機密性傳輸 (任何人可加密,只有持有私鑰者能解密)。
  • 私鑰加密 (簽名),公鑰驗證:完整性/不可抵賴 (持有私鑰者簽名,任何人可驗證)。

1. 金鑰生成 (命令列)

# 產生 RSA 2048 位元私鑰
openssl genrsa -out private.pem 2048

# 從私鑰導出公鑰
openssl rsa -in private.pem -pubout -out public.pem

# 或帶密碼保護私鑰
openssl genrsa -aes256 -out private_enc.pem 2048

2. PHP 程式碼:公鑰加密 / 私鑰解密

<?php
$data = '敏感資料';

// 載入金鑰
$pubKey = openssl_pkey_get_public(file_get_contents('public.pem'));
$privKey = openssl_pkey_get_private(file_get_contents('private.pem')); // 若有密碼:['file'=>'private.pem','passphrase'=>'pwd']

// 公鑰加密
openssl_public_encrypt($data, $encrypted, $pubKey);
echo "Encrypted (base64): " . base64_encode($encrypted) . "\n";

// 私鑰解密
openssl_private_decrypt($encrypted, $decrypted, $privKey);
echo "Decrypted: $decrypted\n"; // 原始資料

// 釋放資源
openssl_free_key($pubKey);
openssl_free_key($privKey);
?>

3. PHP 程式碼:私鑰簽名 / 公鑰驗證

<?php
$data = '重要合約內容';
$privKey = openssl_pkey_get_private(file_get_contents('private.pem'));

// 簽名 (SHA256)
openssl_sign($data, $signature, $privKey, OPENSSL_ALGO_SHA256);
echo "Signature (base64): " . base64_encode($signature) . "\n";

// 驗證
$pubKey = openssl_pkey_get_public(file_get_contents('public.pem'));
$ok = openssl_verify($data, $signature, $pubKey, OPENSSL_ALGO_SHA256);
if ($ok === 1) {
    echo "簽名驗證通過\n";
} elseif ($ok === 0) {
    echo "簽名驗證失敗\n";
} else {
    echo "驗證過程錯誤\n";
}
openssl_free_key($privKey);
openssl_free_key($pubKey);
?>

4. 另一對:私鑰加密 / 公鑰解密 (較少用,用於特定協定)

<?php
openssl_private_encrypt($data, $encrypted, $privKey);
openssl_public_decrypt($encrypted, $decrypted, $pubKey);
// $decrypted === $data
?>

實務應用場景

場景操作金鑰持有者
API 介接簽名驗證私鑰簽名、公鑰驗證客戶端持私鑰,伺服器存公鑰
敏感資料傳輸 (如信用卡)公鑰加密、私鑰解密伺服器發公鑰給客戶端,伺服器存私鑰
授權碼/授權檔私鑰簽名授權資訊廠商簽名,客戶端驗證

安全提醒

  • 私鑰檔案 絕不可 放入版控、部署到前端、硬編碼在程式碼。
  • 生產環境私鑰建議存放於 HSM、KMS 或至少 chmod 600 僅限 root/www-data 讀取。
  • RSA 加密資料長度受限於金鑰長度 (2048-bit 最大 245 bytes),大資料請用「混合加密」:AES 隨機金鑰加密資料 + RSA 加密 AES 金鑰。
  • 簽名演算法建議 SHA256 以上,避免 SHA1/MD5。
copyright © 萬盛學電腦網 all rights reserved