基本生成步驟
- 生成CA根證書
- 生成服務端證書
- 生成客戶端證書(如果需要做雙向認證的話)
1.生成根證書
# 生成root私鑰 openssl genrsa -out root.key 1024 # 根據私鑰創建根證書請求文件,需要輸入一些證書的元信息:郵箱、域名等 openssl req -new -out root.csr -key root.key # 結合私鑰和請求文件,創建根證書,有效期10年 openssl x509 -req -in root.csr -out root.crt -signkey root.key -CAcreateserial -days 3650
2.生成服務端證書
# 創建服務端私鑰 openssl genrsa -out server.key 1024 # 根據私鑰生成請求文件 openssl req -new -out server.csr -key server.key # 結合私鑰和請求文件創建服務端證書,有效期10年 openssl x509 -req -in server.csr -out server.crt -signkey server.key -CA root.crt -CAkey root.key -CAcreateserial -days 3650
如果需要只需要部署服務端證書端話,就可以結束了。拿着server.crt公鑰和server.key私鑰部署在服務器上,然后解析域名到改服務器指向到IP,證書就部署成功了。
3.生成客戶端證書
如果需要做雙向驗證的,也就是服務端要驗證客戶端證書的情況。那么需要在同一個根證書下再生成一個客戶端證書
# 生成私鑰 openssl genrsa -out client.key 1024 # 申請請求文件 openssl req -new -out client.csr -key client.key # 生成證書 openssl x509 -req -in client.csr -out client.crt -signkey client.key -CA root.crt -CAkey root.key -CAcreateserial -days 3650 # 生成客戶端集成證書pkcs12格式的文件,方便瀏覽器或者http客戶端訪問(密碼:123456) openssl pkcs12 -export -clcerts -in client.crt -inkey client.key -out client.p12
4.nginx配置
server { listen 80; listen 443 ssl; server_name asgcode.test.com; ssl on; ssl_certificate /home/zhaoyingjie/asgcode/run/ssl/server.crt; # server公鑰 ssl_certificate_key /home/zhaoyingjie/asgcode/run/ssl/server.key; #server私鑰 ssl_client_certificate /home/zhaoyingjie/asgcode/run/ssl/root.crt; #根級證書公鑰,用於驗證各個二級client ssl_verify_client on; ssl_session_timeout 5m; client_max_body_size 20m; ssl_prefer_server_ciphers on; access_log /data/asgcode/logs/nginx/access.log main; error_log /data/asgcode/logs/nginx/error.log; location / { add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods POST,GET,OPTIONS; add_header Access-Control-Allow-Headers x-requseted-with,content-type; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-For $remote_addr; proxy_headers_hash_max_size 51200; proxy_headers_hash_bucket_size 6400; set_real_ip_from 0.0.0.0/0; real_ip_header X-Forwarded-For; include uwsgi_params; uwsgi_pass 127.0.0.1:7060; } }
5.客戶端請求
python 腳本
import requests import json if __name__ == '__main__': CA_FILE = "/Users/mac/repose/asgcode/run/ssl/root.crt" # 根級證書公鑰 KEY_FILE = "/Users/mac/repose/asgcode/run/ssl/client.key" # 客戶端私鑰 CERT_FILE = "/Users/mac/repose/asgcode/run/ssl/client.crt" # 客戶端公鑰 try: # cert # 通過request()方法創建一個請求: req = requests.get('https://asgcode.test.com/health', cert=(CERT_FILE, KEY_FILE), verify=False) print(req.content) print(req) except Exception as ex: print("Found Error in auth phase:%s" % str(ex))
curl請求
curl -k --cert /Users/mac/repose/asgcode/run/ssl/client.crt --key /Users/mac/repose/asgcode/run/ssl/client.key https://asgcode.guoyafeng.com/health