php_openssl.dll 提供 PHP 呼叫 OpenSSL 庫功能:對稱/非對稱加密、數位簽名、證書管理、TLS/SSL 通訊、PKCS#7/12 處理等。是實作 HTTPS 客戶端、API 簽名驗證、支付加密、憑證產生的基礎。
openssl_public_encrypt/decrypt、openssl_private_encrypt/decrypt、對稱加密 openssl_encrypt/decrypt (AES 等)。openssl_sign/verify、openssl_digest (雜湊)。stream_socket_client/server 搭配 ssl:// 協定。PHP 擴展底層即呼叫同一組庫,CLI 適合離線金鑰管理、除錯。
# RSA 2048 位元,無密碼
openssl genrsa -out private.pem 2048
# RSA 2048,AES-256 加密私鑰 (需輸入密碼)
openssl genrsa -aes256 -out private_enc.pem 2048
# DSA 參數 + 金鑰
openssl dsaparam -out dsaparam.pem 2048
openssl gendsa -out dsa_private.pem dsaparam.pem
openssl rsa -in private.pem -pubout -out public.pem
openssl dsa -in dsa_private.pem -pubout -out dsa_public.pem
# RSA 自簽,有效期 365 天
openssl req -x509 -new -key private.pem -days 365 -out cert.pem -subj "/CN=localhost"
# 產生 CSR (送 CA 簽署)
openssl req -new -key private.pem -out csr.pem -subj "/CN=example.com"
# 加密 (用公開鑰/證書)
openssl smime -encrypt -in plain.txt -out encrypted.p7m -outform DER cert.pem
# 解密 (用私鑰)
openssl smime -decrypt -in encrypted.p7m -inform DER -inkey private.pem -out decrypted.txt
# AES-256-CBC 加密檔案 (互動輸入密碼)
openssl enc -aes-256-cbc -salt -in plain.txt -out encrypted.bin
# 解密
openssl enc -d -aes-256-cbc -in encrypted.bin -out plain.txt
# Base64 編碼/解碼 (非加密,單純編碼)
echo "secret" | openssl enc -base64
echo "c2VjcmV0Cg==" | openssl enc -base64 -d
# 啟動測試 HTTPS 伺服器 (需證書+私鑰)
openssl s_server -key private.pem -cert cert.pem -www -accept 4433
# 客戶端連線測試
openssl s_client -connect localhost:4433 -showcerts
<?php
// 對稱加密 (推薦使用 openssl_encrypt, PHP 7.1+ 支援 AEAD 模式如 AES-GCM)
$data = '機密資料';
$key = random_bytes(32); // 256-bit
$iv = random_bytes(16); // 128-bit IV
$cipher = 'aes-256-gcm';
$encrypted = openssl_encrypt($data, $cipher, $key, OPENSSL_RAW_DATA, $iv, $tag);
$decrypted = openssl_decrypt($encrypted, $cipher, $key, OPENSSL_RAW_DATA, $iv, $tag);
// 非對稱加密
$pub = openssl_pkey_get_public(file_get_contents('public.pem'));
$priv = openssl_pkey_get_private(file_get_contents('private.pem'));
openssl_public_encrypt($data, $enc, $pub);
openssl_private_decrypt($enc, $dec, $priv);
// 簽名驗證
openssl_sign($data, $sig, $priv, 'sha256');
$valid = openssl_verify($data, $sig, $pub, 'sha256');
openssl_free_key($pub);
openssl_free_key($priv);
?>
libeay32.dll/ssleay32.dll (Windows) 未在 PATH。curl.cainfo/openssl.cafile 指向 cacert.pem。