技術文章 · IT 指令工具箱

OpenSSL 指令:查 TLS 憑證、到期日、CSR 與 SHA-256

整理 openssl s_client、x509、req、pkey、dgst 常用指令,包含查網站憑證鏈、SNI、到期日、SAN、CSR、私鑰匹配與 checksum。

作者 Steve Chen · 發布  · 約 6 分鐘閱讀

IT 指令工具箱 — 廷皓技術專欄插圖

OpenSSL 能查憑證與 TLS 握手,也能產生 key/CSR。查詢和產生金鑰要分開看;正式私鑰不得貼到線上工具、工單或版本庫。

21 組範例OpenSSL 3.x/1.1.1 常見用法LinuxmacOS查核日期:2026-08-11
動手前:私鑰、PKCS#12 與含密碼檔案屬敏感資料。產生前確認加密、權限、備份與輪替流程;不要用自簽憑證取代正式信任鏈,除非環境已明確管理信任。

查遠端 TLS

看 TLS 握手與憑證鏈OpenSSL

openssl s_client -connect example.com:443 -servername example.com -showcerts </dev/null

-servername 提供 SNI;輸出很長。

只看握手摘要OpenSSL

openssl s_client -connect example.com:443 -servername example.com -brief </dev/null

-brief 支援度依 OpenSSL 版本。

強制 TLS 1.2OpenSSL

openssl s_client -connect example.com:443 -servername example.com -tls1_2 </dev/null

用於相容性測試,不代表應停用 TLS 1.3。

強制 TLS 1.3OpenSSL

openssl s_client -connect example.com:443 -servername example.com -tls1_3 </dev/null

OpenSSL 與伺服器都需支援。

顯示協商 ALPNOpenSSL

openssl s_client -connect example.com:443 -servername example.com -alpn 'h2,http/1.1' </dev/null

可看是否協商 HTTP/2。

測試 STARTTLS SMTPOpenSSL

openssl s_client -starttls smtp -connect mail.example.com:587 -servername mail.example.com </dev/null

不同郵件服務 port 與政策不同。

讀取憑證與 CSR

查看本機憑證完整文字OpenSSL

openssl x509 -in cert.pem -noout -text

不輸出私鑰。

只看 Subject、Issuer、日期OpenSSL

openssl x509 -in cert.pem -noout -subject -issuer -dates

快速盤點簽發者與有效期。

看 SANOpenSSL

openssl x509 -in cert.pem -noout -ext subjectAltName

SAN 才是現代主機名稱驗證重點。

檢查 30 天內是否到期OpenSSL

openssl x509 -in cert.pem -noout -checkend 2592000

結束碼可供監控;2592000 秒約 30 天。

查看 CSROpenSSL

openssl req -in request.csr -noout -text -verify

確認 subject、SAN 與 CSR 簽章。

驗證憑證鏈OpenSSL

openssl verify -CAfile ca-chain.pem cert.pem

CAfile 需包含正確信任鏈。

查看 PKCS#12 內容但不輸出 keyOpenSSL

openssl pkcs12 -in bundle.p12 -info -noout

會互動要求匯入密碼。

金鑰、CSR 與摘要

產生 Ed25519 私鑰OpenSSL 3.x

openssl genpkey -algorithm ED25519 -out private-key.pem

先確認目標服務支援 Ed25519。

產生 RSA 3072 私鑰OpenSSL

openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out private-key.pem

產生後立即 chmod 600 並安全備份。

查看公鑰資訊OpenSSL

openssl pkey -in private-key.pem -pubout -text_pub -noout

會讀私鑰,環境權限要安全。

檢查私鑰結構OpenSSL

openssl pkey -in private-key.pem -check -noout

會依 key 是否加密要求密碼。

從私鑰產生 CSROpenSSL

openssl req -new -key private-key.pem -out request.csr

SAN 通常要透過 config 或 -addext 明確指定。

產生含 SAN 的 CSROpenSSL

openssl req -new -key private-key.pem -out request.csr -subj '/CN=example.com' -addext 'subjectAltName=DNS:example.com,DNS:www.example.com'

-addext 支援度依版本;CN 不能取代 SAN。

計算 SHA-256OpenSSL

openssl dgst -sha256 download.iso

可與發布者提供的可信摘要比對。

產生 32 bytes 隨機值OpenSSL

openssl rand -hex 32

適合產生隨機 material;實際 secret 管理仍需安全儲存。

怎麼確認有做對

  • s_client 最後的 Verify return code 應符合預期。
  • 核對 SAN、Issuer、Not Before/After 與完整 chain。
  • CSR 簽發前再次查看內容,確認沒有錯誤網域或組織資訊。

常見錯誤

  • 忘記 SNI,查到預設站台憑證。
  • 只看 CN,忽略 SAN。
  • 把私鑰貼到線上檢查工具。
  • 用 -noverify 或忽略 verify error 當成完成。

版本與官方文件

參數會隨工具版本與作業系統實作改變。正式環境先用 --help、-h 或系統內建說明確認,再以當版官方文件為準。

聯絡廷皓討論 看更多文章