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 生成 SSL 證書完整教學

編輯:Linux 教學

前言

在配置 SSL 環境時,OpenSSL 是最常用的工具之一。本文將詳細記錄從安裝 OpenSSL 到生成伺服器端與客戶端證書、建立私有 CA、簽署憑證,以及最終在 Apache 中配置雙向驗證的完整流程,供有需要的朋友參考。

一、環境準備與目錄結構

1. 安裝 OpenSSL

sudo apt-get install openssl

2. 建立工作目錄與 CA 結構

依據 OpenSSL 預設配置(通常位於 /etc/ssl/openssl.cnf),在工作目錄下建立必要的目錄與檔案:

mkdir -p ./demoCA/{private,newcerts}
touch ./demoCA/index.txt
touch ./demoCA/serial

注意: serial 檔案中需寫入 01,index.txt 保持為空檔案。

二、生成伺服器端金鑰與憑證請求 (CSR)

1. 生成伺服器私鑰

openssl genrsa -des3 -out server.key 1024

執行時會提示輸入密碼,此密碼用於加密金鑰檔案。若嫌麻煩,可移除密碼:

openssl rsa -in server.key -out server.key

2. 生成伺服器憑證簽署請求 (CSR)

openssl req -new -key server.key -out server.csr

依提示填寫資訊(Country: CN, Province: china, City: Zhuhai, Organization: xxxx Ltd, OU: jecks, Common Name: www.qiuicai.com, Email: xxx@qiujicai.com)。生成的 server.csr 需提交給 CA 簽署。

三、生成客戶端金鑰與 CSR

步驟與伺服器端相同:

openssl genrsa -des3 -out client.key 1024
openssl req -new -key client.key -out client.csr

填寫資訊時,Common Name 可設為客戶端識別名稱。

四、建立私有 CA (根憑證)

openssl req -new -x509 -keyout ca.key -out ca.crt

此命令會同時生成 CA 私鑰 (ca.key) 與自簽根憑證 (ca.crt),有效期預設為 1 年。

五、使用 CA 簽署伺服器與客戶端憑證

1. 簽署伺服器憑證

openssl ca -in server.csr -out server.crt -cert ca.crt -keyfile ca.key

確認簽署資訊無誤後輸入 y 完成簽署,生成 server.crt。

2. 簽署客戶端憑證

openssl ca -in client.csr -out client.crt -cert ca.crt -keyfile ca.key

若遇到國家代碼大小寫不匹配錯誤,請確保 CSR 與 CA 設定一致(均為 CN)。

3. 轉換客戶端憑證為 PKCS#12 格式 (供瀏覽器匯入)

openssl pkcs12 -export -in client.crt -inkey client.key -out client.pfx

需設定匯出密碼,此為瀏覽器匯入時所需密碼。

六、檔案用途總結

  • Client 端需求: ca.crt, client.crt, client.key, client.pfx
  • Server 端需求: ca.crt, server.crt, server.key

七、Apache 雙向 SSL 配置範例

編輯 /etc/apache2/sites-enabled/000-default (或對應虛擬主機配置檔):

NameVirtualHost *:443

<VirtualHost *:443>
    ServerSignature On
    SSLEngine On
    SSLCertificateFile /usr/local/apache/conf/ssl.crt/server.crt
    SSLCertificateKeyFile /usr/local/apache/conf/ssl.crt/server.key
    SSLCACertificatePath /usr/local/apache/conf/ssl.crt
    SSLCACertificateFile /usr/local/apache/conf/ssl.crt/ca.crt

    # 啟用客戶端憑證驗證
    SSLVerifyClient require
    SSLVerifyDepth 1

    ServerAdmin webmaster@localhost
    ServerName www.qiujicai.com
    DocumentRoot /var/www/test
    <Directory /var/www/test/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
    </Directory>
</VirtualHost>

八、客戶端憑證安裝與驗證

  1. 將 ca.crt 安裝至「信任的根憑證授權機構」
  2. 將 client.pfx 匯入瀏覽器 (IE/Edge/Chrome) 個人憑證存儲,輸入匯出密碼
  3. 使用 HTTPS 訪問伺服器,瀏覽器將提示選擇客戶端憑證完成雙向驗證

結語

透過上述步驟,即可建立一套完整的私有 PKI 體系,實現伺服器身份驗證與客戶端憑證雙向驗證。實際部署時,建議使用 2048 位或更高強度的金鑰,並妥善保管 CA 私鑰與各端密碼。

Copyright © Windows教程網 All Rights Reserved