都 1202 年了,使用 SSL 加密應該都是標配了吧,市面上也有不少可以免費申請的證書,如:Let's Encrypt 和 ZeroSSL ,但有效期一般只有 3 個月,最長的 Buypass 也只有 6 個月(由於眾所周知的原因去除了與大陸有關聯的簽發機構)。對於內部使用和測試就顯得不友好,在這種情況下自簽章證書也是個不錯的選擇 (總不可能連自己都不信認吧
# 安裝環境
自簽章證書需要用到 openssl 生成,所以系統上必須安裝 openssl (一般都已經預先安裝好了)
打開終端,輸入 openssl version 並回車,如果打印出 openssl 版本則表明已安裝,如果提示有「not found」則未安裝
執行安裝命令 sudo apt install openssl 安裝 openssl
# 創建自签名 SSL 證書
- 創建 Private key
openssl ecparam -genkey -name prime256v1 -out <KeyFile.key> |
-name prime256v1 : 使用 ECC(prime256v1)算法創建 Private key-out <KeyFile.key> : 將創建 Private key 命名為 KeyFile.key
- 創建證書簽章請求(CSR)
openssl req -new -sha512 -key <KeyFile.key> -out <ReqFile.req> |
-new -sha512 : 使用 - sha512 算法創建一個 CSR-key <KeyFile.key> : 選擇步驟(1)創建的 KeyFile.key-out <ReqFile.req> : 將創建 CSR 命名為 ReqFile.req
- 對證書進行簽章
openssl x509 -req \ | |
-sha512 \ | |
-days <validity period> \ | |
-in <ReqFile.req> \ | |
-signkey <KeyFile.key> \ | |
-out <PEMFile.crt> |
-days <validity period> : 證書有效期,單位為天「day」,365 day 即為 1 year-in <ReqFile.req> : 選擇步驟(2)創建的證書簽章請求 ReqFile.req-signkey <KeyFile.key> : 使用私鑰 KeyFile.key 進行簽章-out <PEMFile.crt> : 將簽章後的證書導出並命名為 PEMFile.crt
# 實例
- 創建用於泛域名證書的 Private key
openssl ecparam -genkey -name prime256v1 -out ca.key |
- 創建證書簽章請求(CSR)
openssl req -new -sha512 -key ca.key -out ca.req |
- 對證書進行簽章
openssl x509 -req \ | |
-sha512 \ | |
-days 3650 \ | |
-in ca.req \ | |
-signkey ca.key \ | |
-out ca.crt |
更多選項可以參考官方文檔
執行命令後會生成私鑰,並詢問一系列與生成證書有關的問題,輸入所需要的资讯後將創建證書和私鑰檔案
C= : 國家 / 地區名稱,使用 ISO 3166-1 alpha-2 codes 標準ST= : 州或省名稱L= : 地區(市)名稱O= : 機構名稱OU= : 機構內部門名稱CN= : 限定域名
證書和私鑰所在的路徑為執行命令時所在的路徑,在該路徑下執行 ls 命令,如果執行成功則可以看到生成的「ca.crt」、「ca.key」档案
# 將证书和密鑰轉換為 PFX 格式
openssl pkcs12 -in example.cer \ | |
-inkey example.key \ | |
-export \ | |
-out example.pfx \ | |
-password pass:123456 |
-in : 需要轉換的證書,此處為「example.cer」-inkey : 需要轉換的密鑰,此處為「example.key」-out : 轉換後輸出的 pfx 檔案名稱,此處為「example.pfx」-password pass: : 設置 pfx 證書的密碼,此處為「123456」,如果留空則不設置密碼