https相較於http而言有很大的安全性,當咱們一個服務開啓https並與之通訊時,每每須要證書的認證,若是是瀏覽器訪問服務,只要在瀏覽器內設置信任證書便可,而若是是程序內訪問服務(如java程序),則須要導入該服務的證書所信任的證書。java
實際狀況中,內部系統的互相通訊使用https,每每不可能向公有CA申請證書(申請證書須要很高的費用),故咱們須要建立一個私有CA來申請證書實現https通訊。web
詳見個人一篇博文:https簡單解讀segmentfault
CA要給別人簽發證書,首先本身得有一個做爲根證書,咱們得在一切工做以前修改好CA的配置文件、序列號、索引等等。centos
輸入如下命令更改配置文件:瀏覽器
vi /etc/pki/tls/openssl.cnf
配置文件更改如下部分:安全
[ CA_default ] dir = /etc/pki/CA # Where everything is kept certs = $dir/certs # Where the issued certs are kept crl_dir = $dir/crl # Where the issued crl are kept database = $dir/index.txt # database index file. #unique_subject = no # Set to 'no' to allow creation of # several ctificates with same subject. new_certs_dir = $dir/newcerts # default place for new certs. certificate = $dir/cacert.pem # The CA certificate serial = $dir/serial # The current serial number crlnumber = $dir/crlnumber # the current crl number # must be commented out to leave a V1 CRL crl = $dir/crl.pem # The current CRL private_key = $dir/private/cakey.pem # The private key RANDFILE = $dir/private/.rand # private random number file ... default_days = 3650 # how long to certify for ... # For the CA policy [ policy_match ] countryName = match stateOrProvinceName = optional localityName = optional organizationName = optional organizationalUnitName = optional commonName = supplied emailAddress = optional
在/etc/pki/CA目錄建立兩個文件index.txt和serial:服務器
cd /etc/pki/CA && touch index.txt serial && echo 01 > serial
仍在當前目錄下生成一個CA私鑰cakey.pem和自簽證書cacert.pem:dom
openssl genrsa -out private/cakey.pem 2048 openssl req -new -x509 -key private/cakey.pem -out cacert.pem
生成公鑰的時候會提示輸入一些信息,例子以下:操作系統
Country Name (2 letter code) []:CN #國家名 State or Province Name (full name) []:hangzhou #省份名 Locality Name (eg, city) []:hangzhou #地名 Organization Name (eg, company) []:company #公司名 Organizational Unit Name (eg, section) []:unit #部門名 Common Name (eg, your websites domain name) []:localhost #服務域名 Email Address []: #電子郵件
後面一些信息可按回車略過code
這裏比較重要的是Comman Name填寫的是服務的域名地址,即若是該證書用於某個服務則填該服務的域名地址(如用於百度服務器,則填寫www.baidu.com)
本方案的CA證書不用於某個服務,故可填localhost
爲一個服務生成私鑰server.key和一個證書請求文件server.csr:
openssl genrsa -out server.key 2048 openssl req -new -key server.key -out server.csr
生成證書請求文件時,仍會提示輸入一些信息,例子以下:
Country Name (2 letter code) []:CN #國家名 State or Province Name (full name) []:hangzhou #省份名 Locality Name (eg, city) []:hangzhou #地名 Organization Name (eg, company) []:company #公司名 Organizational Unit Name (eg, section) []:unit #部門名 Common Name (eg, your websites domain name) []:XXX.XXX.XXX #服務域名 Email Address []: #電子郵件
這裏的Common Name就應該填你實際服務所用的域名了
下面將該證書請求文件server.csr由你構建的私有CA簽署,生成一個server.crt證書:
openssl x509 -req -in server.csr -CA /etc/pki/CA/cacert.pem -CAkey /etc/pki/CA/private/cakey.pem -CAcreateserial -out server.crt
到此爲止,server.crt證書可用於服務提供https訪問,客戶端若想訪問該服務,導入CA根證書cacert.pem便可。