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

Linux OpenSSL 自建 CA 與 CSR 憑證簽署完整實作教學

編輯:Linux 教學

企業內部測試環境或私有服務常需自簽憑證。本文記錄使用 OpenSSL 建立私有 CA、產生伺服器金鑰與 CSR、CA 簽署憑證的標準流程,適用於 HTTPS、LDAPS、VPN 等場景。

環境與目錄規劃

CA 根目錄:/etc/pki/CA
  ├── private/cakey.pem      # CA 私鑰
  ├── cacert.pem             # CA 自簽憑證
  ├── certs/                 # 已簽發憑證備份
  ├── newcerts/              # 簽發流程暫存
  ├── crl/                   # 撤銷清單
  ├── index.txt              # 簽發索引
  └── serial                 # 序號檔

步驟 1:調整 OpenSSL 設定檔

編輯 /etc/pki/tls/openssl.cnf,[ CA_default ] 區段指向上述目錄:

dir = /etc/pki/CA
certs = $dir/certs
crl_dir = $dir/crl
database = $dir/index.txt

步驟 2:建立 CA 私鑰與自簽憑證

cd /etc/pki/CA
# 產生 2048-bit RSA 私鑰,權限 0600
(umask 077; openssl genrsa 2048 > private/cakey.pem)

# 自簽 CA 憑證,有效期 10 年(3655 天)
openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 3655
# 依提示填寫 Country、Organization、Common Name (CA 名稱) 等

步驟 3:初始化 CA 工作目錄

mkdir -p certs newcerts crl
touch index.txt serial
echo 01 > serial

步驟 4:伺服器端產生私鑰與 CSR

於應用伺服器(如 HTTPD)執行:

# 產生 2048-bit 私鑰(生產環境建議 4096)
openssl genrsa 2048 > httpd.key

# 產生 CSR,含公鑰與主體資訊
openssl req -new -key httpd.key -out httpd.csr
# Common Name 必須填寫服務完整網域名(FQDN)

步驟 5:CA 簽署 CSR 產生伺服器憑證

將 httpd.csr 傳至 CA 機器,執行:

openssl ca -in httpd.csr -out httpd.crt -days 365
# 簽署過程會更新 index.txt、serial

簽署完成後,將 httpd.crt、httpd.key 部署至應用伺服器,配置服務啟用 HTTPS。

進階補充

  • SAN(Subject Alternative Name)支援: CSR 階段加入 -addext "subjectAltName=DNS:example.com,DNS:www.example.com"(OpenSSL 1.1.1+)。
  • 中繼 CA: 同樣流程,但 CA 憑證由上層 CA 簽署,basicConstraints=critical,CA:TRUE,pathlen:0。
  • 撤銷憑證: openssl ca -revoke certs/xxx.pem 並產生 CRL openssl ca -gencrl -out crl/ca.crl。
  • 自動化: 可搭配 certbot、cfssl、smallstep 等工具建立 PKI 自動化管線。

常見坑點

現象原因解決
簽署報 failed to update databaseindex.txt 格式錯誤或權限不足確保 index.txt 為空檔、CA 目錄擁有者為 root:root、權限 700
瀏覽器提示「不受信任」根憑證未匯入信任存儲將 cacert.pem 匯入 OS/瀏覽器信任根憑證清單
Common Name 不符CSR 的 CN 與實際訪問網域不同重新產生 CSR,CN 填寫完整 FQDN
Copyright © Windows教程網 All Rights Reserved