1. 程式人生 > >使用CA自簽名證書搭建HTTPS網站

使用CA自簽名證書搭建HTTPS網站

在自己倒騰https網站的時候用自定義的CA給自己的網站做自簽名的問題一直困擾了我好久,下面是我自己測試成功的案例,網上有很多類似的問題,在這裡儲備一份供自己和他人蔘考使用。

1. 安裝linux,apache,openssl元件,在此不做贅述,我用的就是centos裡自帶的apache和openssl。

2. 生成自簽名的CA證書

(1) 生成CA私鑰
[root@localhost ~]# openssl genrsa -out ca.key 2048

# 在當前目錄下生成ca.key檔案,這個檔案是下一步生成CA證書的私鑰。
(2) 生成CA自簽名證書
#方法一:如果需要使用第三方CA簽發證書
[root@localhost ~]# openssl req -new -key ca.key -out ca.req -config /etc/pki/tls/openssl.cnf [root@localhost ~]# openssl req -x509 -key ca.key -in ca.req -out ca.crt -days 3650 -config /etc/pki/tls/openssl.cnf #方法二:如果就伺服器本機就是CA,則可以將上述兩個操作合併為一個操作(如下命令),它在自簽署過程中將在記憶體中自動建立證書請求檔案,當然,既然要建立證書請求檔案,就需要人為輸入申請者的資訊了。
[root@localhost ~]# openssl req -new -x509 -days 3650 -key ca.key -out ca.crt -config /etc/pki/tls/openssl.cnf # 在當前目錄下生成ca.crt這個檔案,這個就是CA證書了,其他伺服器和客戶端的證書都是用ca.crt這個檔案簽發的。

3. 生成伺服器證書

(1) 生成伺服器端的私鑰
[root@localhost ~]# openssl genrsa -out server.key 2048 

# 在當前目錄下生成server.key檔案,這個檔案是伺服器段的私鑰。
(2) 生成伺服器端的簽署申請
[[email protected] ~]# openssl req -new -out server.csr -key server.key -config /etc/pki/tls/openssl.cnf 

# 在當前目錄下生成server證書的簽署申請,後面用CA給伺服器簽署證書的時候需要用到這個申請檔案。
# 生成簽署申請的過程中需要填寫一些資訊,按提示要求填寫即可
# 但需要說明的是Common Name必須和ssl.conf裡面的ServerName一致
# 否則客戶端訪問的時候會提示證書資訊不能認證。
(3) 使用CA證書給伺服器端簽署伺服器證書

進入/etc/pki/CA目錄下,在裡面建立一個index.txt空檔案,以及一個名為serial,內容為01的檔案

[root@localhost ~]# touch /etc/pki/CA/index.txt
[root@localhost ~]# touch /etc/pki/CA/serial
[root@localhost ~]# echo "01" >> /etc/pki/CA/serial

執行簽署證書命令

[[email protected] ~]# openssl ca -in server.csr -out server.crt -cert ca.crt -keyfile ca.key -config /etc/pki/tls/openssl.cnf

# 這個server.crt就是由CA簽發的伺服器證書。 

4. 配置ssl.conf

將我們生成的server.crt,server.key,ca.crt三個檔案複製到/usr/local/apache2/conf/ssl.crt目錄下
編輯ssl.conf檔案,修改SSLCertificateFile,SSLCertificateKeyFile,SSLCACertificatePath,SSLCACertificateFile幾個配置項如下:

SSLCertificateFile "/usr/local/apache2/conf/ssl.crt/liveupdate_server.crt"
SSLCertificateKeyFile "/usr/local/apache2/conf/ssl.crt/server.key"
SSLCACertificatePath "/usr/local/apache2/conf/ssl.crt"
SSLCACertificateFile "/usr/local/apache2/conf/ssl.crt/ca.crt"

重啟apache服務

# 如果是用yum安裝的apache服務
[root@localhost ~]# service httpd restart 
# 如果是用原始碼安裝的apache服務
[root@localhost ~]# /usr/local/apache2/bin/apachectl -k restart

5. 在PC端匯入CA證書到受信任的根證書頒發機構,即可實現https訪問