當初:
原來的x.509證書,生成就一行程式碼,非常方便:
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout key.pem -out cert.pem
然後按照提示輸入機構和dns資訊即可。
然而:
最近在開發一個websocket專案時,需要使用wss協議,在機器A(win7)上除錯沒問題,在機器B(win10+go1.22.3)上除錯,報錯:
PS E:\zjw\golang\ws> go run ws/server1wss/client 2024/10/30 15:45:37 Error connecting to server: x509: certificate relies on legacy Common Name field, use SANs instead
經查,go1.15以後的版本廢棄了依賴Common Name欄位的x509證書,必須使用SANs證書。SANs是Subject Alternate Names的簡稱,它支援新增多個域名,允許將多個域名寫入同一個證書中,這樣就可以保護多個域名,從而降低了運維人員的管理成本,提高了證書管理效率。
採用如下方法建立證書:
1.首先安裝openssl。步驟略。
2.建立私鑰:
PS E:\zjw\ca_fsd> openssl genrsa -des3 -out fusude.com.key 2048
3. 生成CSR
PS E:\zjw\ca_fsd> openssl req -new -key fusude.com.key -out fusude.com.csr
Enter pass phrase for fusude.com.key:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:CN
State or Province Name (full name) [Some-State]:hebei
Locality Name (eg, city) []:shijiazhuang
Organization Name (eg, company) [Internet Widgits Pty Ltd]:fusude
Organizational Unit Name (eg, section) []:dept
Common Name (e.g. server FQDN or YOUR name) []:zjw
Email Address []:zjw@fusude.com
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:*********
An optional company name []:fusude
4. 從秘鑰中刪除密碼(特別提示:密碼要用到,另外記好!)
PS E:\zjw\ca_fsd> cp fusude.com.key fusude.com.key.org PS E:\zjw\ca_fsd> openssl rsa -in fusude.com.key.org -out fusude.com.key
5. 為SAN證書建立config file,名字無所謂,例如叫v3.txt,內容如下。注意subjectAltName裡,設定你需要的DNS Name
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer:always
basicConstraints = CA:TRUE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment, keyAgreement, keyCertSign
subjectAltName = DNS:fusude.com, DNS:*.fusude.com
issuerAltName = issuer:copy
6. 建立自簽名證書:
PS E:\zjw\ca_fsd> openssl x509 -req -in fusude.com.csr -signkey fusude.com.key -out fusude.com.crt -days 3650 -sha256 -extfile v3.txt
Signature ok
subject=C = CN, ST = hebei, L = shijiazhuang, O = fusude, OU = dept, CN = zjw, emailAddress = zjw@fusude.com
Getting Private keys
生成的檔案fusude.com.crt即為我們需要的SANs證書。
7. 還可以轉換為pfx或pem格式:
PS E:\zjw\ca_fsd> openssl pkcs12 -export -out fusude.com.pfx -inkey fusude.com.key -in fusude.com.crt Enter Export Password: Verifying - Enter Export Password:
PS E:\zjw\ca_fsd> openssl pkcs12 -export -out fusude.com.pem -inkey fusude.com.key -in fusude.com.crt Enter Export Password: Verifying - Enter Export Password:
8. 證書的使用不展開論述。感謝觀看。
感謝Azure Lei Zhang的部落格 : Azure Application Gateway (6) 使用OpenSSL建立SAN證書