Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

OpenSSL 互轉 X.509 (PEM/CRT/KEY) 與 PFX (PKCS#12) 證書格式完整指令

編輯:Linux 教學

X.509(PEM/CRT/KEY)與 PFX(PKCS#12)是兩大主流證書容器格式,Linux/Unix 常用前者,Windows/IIS/Java KeyStore 常用後者。openssl pkcs12 子命令可實現雙向無損轉換。

X.509 → PFX(含私鑰、憑證鏈)


# 輸入:server.key(私鑰)、server.crt(葉子憑證+中繼鏈)
# 輸出:server.pfx(加密容器)
openssl pkcs12 -export \
    -inkey server.key \
    -in server.crt \
    -out server.pfx \
    -name "my-server" \
    -CAfile ca-bundle.crt \
    -caname "Root CA"

執行時會提示設定**匯出密碼**(PFX 加密密碼),匯入 IIS/Windows 時需提供。

PFX → X.509(拆解為私鑰、憑證、鏈)


# 1. 一次性導出所有明文內容到 PEM
openssl pkcs12 -in server.pfx -nodes -out server.pem
# 輸入 PFX 密碼,server.pem 含:私鑰 + 葉子憑證 + 中繼 CA + 根 CA

# 2. 從 PEM 提取私鑰(去除密碼)
openssl rsa -in server.pem -out server.key

# 3. 從 PEM 提取葉子憑證
openssl x509 -in server.pem -out server.crt

# 4. (可選)提取 CA 鏈
# 手動編輯 server.pem,保留 BEGIN/END CERTIFICATE 區塊中的中繼/根 CA,存為 ca-chain.crt

常用參數速查表

參數作用
-export建立 PFX(輸出模式)
-inkey指定私鑰檔(PEM 格式)
-in輸入檔(憑證或 PFX)
-out輸出檔
-nodes不加密私鑰(導出時),僅用於測試/自動化,生產請加密
-namePFX 內部別名(Windows 憑證存儲顯示用)
-CAfile匯入時指定 CA 鏈檔
-canameCA 別名
-passin pass:xxx非互動式指定輸入密碼
-passout pass:xxx非互動式指定輸出密碼

自動化腳本範例(CI/CD 適用)


#!/bin/bash
# pfx_to_pem.sh   
set -euo pipefail
PFX=$1; OUT=$2; PASS=$3
mkdir -p "$OUT"
openssl pkcs12 -in "$PFX" -nodes -passin "pass:$PASS" -out "$OUT/all.pem"
openssl rsa -in "$OUT/all.pem" -out "$OUT/private.key"
openssl x509 -in "$OUT/all.pem" -out "$OUT/cert.crt"
# 提取 CA 鏈(簡易 grep,實際建議用 awk 分段)
awk '/BEGIN CERTIFICATE/,/END CERTIFICATE/' "$OUT/all.pem" | tail -n +$(($(grep -n 'END CERTIFICATE' "$OUT/all.pem" | head -1 | cut -d: -f1)+1)) > "$OUT/ca-chain.crt"
echo "Done: $OUT/private.key, $OUT/cert.crt, $OUT/ca-chain.crt"

格式對照表

格式副檔名編碼典型用途
X.509 PEM.pem .crt .cerBase64 + 標頭尾Nginx、Apache、Linux 服務
Private Key PEM.key .pemBase64 + 標頭尾同上
PKCS#12.pfx .p12二進制 DER + 加密Windows IIS、Java KeyStore、Tomcat
PKCS#7.p7b .p7cBase64 僅含憑證鏈Windows、Java

掌握上述指令,即可在異構平台間自由流轉 TLS 憑證資產。

Copyright © Windows教程網 All Rights Reserved