1. 程式人生 > 實用技巧 >生成自簽名證書的兩種方式

生成自簽名證書的兩種方式

有些時候我們需要生成自簽名的ssl證書,該博文用於記錄下生成ssl證書的兩種方式。

一、通過github上的專案來生成(比較簡單)

此方式不要求域名可以在公網解析(其實此專案就是封裝了openssl指令,做了一個自動版的openssl生成證書)。

1.1 下載專案並設定有效期

[root@test nginx]# git clone https://github.com/Fishdrowned/ssl.git
[root@test nginx]# cd ssl      # 進入下載的目錄
# 設定證書的有效期(可選配置)
[root@test ssl]# cat ca.cnf | grep days     # ca.cnf檔案中有一些預設設定
default_days    = 3650        # 此處是設定證書的有效期(預設為730天,也就是兩年),我這裡直接修改為十年
# 設定根證書的有效期(可選配置)
[root@test ssl]# cat gen.root.sh | grep days     # 就是此檔案
    -new -x509 -days 7300 -out out/root.crt \     # 預設天數為7300(二十年)


1.2 生成證書

[root@test ssl]# ./gen.cert.sh www.ljz.com      # 執行此指令碼即可,後面的www.ljz.com是你的域名

指令碼執行後,輸出大概如下(所有和證書相關的檔案都會儲存在當前目錄的out目錄下):

1.3 將所需證書檔案copy到其他目錄,以便統一管理

[root@test ssl]# mkdir -pv /data/ssl/www.ljz.com   # 此目錄用於存放證書檔案
# *.key.pem為證書私鑰
[root@test ssl]# cp out/www.ljz.com/www.ljz.com.key.pem /data/ssl/www.ljz.com/
# *.bundle.crt為證書
[root@test ssl]# cp out/www.ljz.com/www.ljz.com.bundle.crt /data/ssl/www.ljz.com/
# root.crt為根證書(此證書用於給client使用,載入到瀏覽器中,以便信任這個證書)
[root@test ssl]# cp out/www.ljz.com/root.crt /data/ssl/www.ljz.com/
[root@test ssl]# ./flush.sh        # 證書相關檔案copy走後,可以執行此指令碼來清空所有歷史(非必須執行)。

至此,只要在你的網站中指定證書及其私鑰的位置,即可通過https來訪問你的網站了。(若不將root.crt匯入到client的瀏覽器,https訪問時會提示不安全。)

二、Let's encrypt

注:此方式需要你的域名必須可以在公網解析。

Let’s Encrypt 是一個自動簽發 https 證書的免費專案
CertbotLet’s Encrypt 官方推薦的證書生成客戶端工具。

注:每種作業系統及要繫結證書的網站不同,對應的安裝操作可能也有出入,我這裡以證書是在centos 7上給nginx使用,若你們的需求和我不一樣,可以去官網查詢安裝過程。

2.1 letsencrypt有什麼限制

  • 同一個頂級域名下的二級域名,一週做多申請 20 個
  • 一個域名一週最多申請 5 次
  • 1 小時最多允許失敗 5 次
  • 請求頻率需要小於 20 次/s
  • 一個 ip 3 小時內最多建立 10 個賬戶
  • 一個賬戶最多同時存在 300 個 pending 的稽核

2.2 配置yum

[root@nginx ~]# yum -y install epel-release 
[root@nginx ~]# yum -y install yum-utils
[root@nginx ~]# yum-config-manager --enable rhui-REGION-rhel-server-extras rhui-REGION-rhel-server-optional

2.3 安裝certbor

[root@nginx ~]# yum -y install certbot python2-certbot-nginx
[root@nginx ~]# certbot --version         # 確定已安裝
certbot 1.3.0

2.4 以命令互動方式開始製作證書

[root@nginx ~]# certbot certonly      # 進入互動模式
Saving debug log to /var/log/letsencrypt/letsencrypt.log

How would you like to authenticate with the ACME CA?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: Nginx Web Server plugin (nginx)   # 此方式需要修改配置檔案
2: Spin up a temporary webserver (standalone)     # 此方式需要停止服務
3: Place files in webroot directory (webroot)     # 如果需要不影響伺服器正常執行的情況下製作證書,可以選擇這種方式
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate number [1-3] then [enter] (press 'c' to cancel): 1
# 在這裡我們輸入1,選擇為nginx外掛
Plugins selected: Authenticator nginx, Installer None
Enter email address (used for urgent renewal and security notices) (Enter 'c' to
cancel): [email protected]        # 這裡輸入你的郵箱賬號(只有第一次使用時會出現)
Starting new HTTPS connection (1): acme-v02.api.letsencrypt.org

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
agree in order to register with the ACME server at
https://acme-v02.api.letsencrypt.org/directory
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(A)gree/(C)ancel: a       # 輸入“a”同意(只有第一次使用時會出現)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing to share your email address with the Electronic Frontier
Foundation, a founding partner of the Let's Encrypt project and the non-profit
organization that develops Certbot? We'd like to send you email about our work
encrypting the web, EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: y          # 輸入“y”確認
Starting new HTTPS connection (1): supporters.eff.org
Please enter in your domain name(s) (comma and/or space separated)  (Enter 'c'
to cancel): www.lvjianzhao.top          # 這裡輸入你的域名
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for www.lvjianzhao.top
nginx: [error] invalid PID number "" in "/run/nginx.pid"
Waiting for verification...
Cleaning up challenges

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/www.lvjianzhao.top/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/www.lvjianzhao.top/privkey.pem
   Your cert will expire on 2020-07-18. To obtain a new or tweaked
   version of this certificate in the future, simply run certbot
   again. To non-interactively renew *all* of your certificates, run
   "certbot renew"
 - Your account credentials have been saved in your Certbot
   configuration directory at /etc/letsencrypt. You should make a
   secure backup of this folder now. This configuration directory will
   also contain certificates and private keys obtained by Certbot so
   making regular backups of this folder is ideal.
 - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
   Donating to EFF:                    https://eff.org/donate-le

 - We were unable to subscribe you the EFF mailing list because your
   e-mail address appears to be invalid. You can try again later by
   visiting https://act.eff.org.


# 假如你的域名解析沒有問題,那麼至此就是證書製作成功了。

2.5 配置nginx使用生成的證書

[root@nginx ~]# cd /etc/letsencrypt/live/www.lvjianzhao.top/     # 進入證書存放目錄
[root@nginx www.lvjianzhao.top]# ll
total 4
# 下面兩個檔案無需關注
lrwxrwxrwx 1 root root  42 Apr 19 21:20 cert.pem -> ../../archive/www.lvjianzhao.top/cert1.pem
lrwxrwxrwx 1 root root  43 Apr 19 21:20 chain.pem -> ../../archive/www.lvjianzhao.top/chain1.pem
# 下面是證書檔案
lrwxrwxrwx 1 root root  47 Apr 19 21:20 fullchain.pem -> ../../archive/www.lvjianzhao.top/fullchain1.pem  
# 下面是證書私鑰
lrwxrwxrwx 1 root root  45 Apr 19 21:20 privkey.pem -> ../../archive/www.lvjianzhao.top/privkey1.pem
# 此README為上面幾個檔案的作用說明
-rw-r--r-- 1 root root 692 Apr 19 21:20 README
# 將所需證書及其私鑰copy到指定目錄統一存放
[root@nginx www.lvjianzhao.top]# cp fullchain.pem privkey.pem /etc/nginx/ssl/www.lvjianzhao.top/
# 接下來就是要修改nginx的配置檔案來引用這個證書了,不過關於nignx的配置檔案修改不是此博文的重點,所以就不解釋了
[root@nginx nginx]# egrep -v '^$|^#' nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
include /usr/share/nginx/modules/*.conf;
events {
    worker_connections 1024;
}
http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    access_log  /var/log/nginx/access.log  main;
    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;
    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;
    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;
    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  www.lvjianzhao.top;
        root         /usr/share/nginx/html;
        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;
        location / {
	    return 302 https://www.lvjianzhao.top;
        }
        error_page 404 /404.html;
            location = /40x.html {
        }
        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }
    server {
        listen       443 ssl http2 default_server;
        listen       [::]:443 ssl http2 default_server;
        server_name  www.lvjianzhao.top;
        root         /usr/share/nginx/html;
        ssl_certificate "/etc/nginx/ssl/www.lvjianzhao.top/fullchain.pem";
        ssl_certificate_key "/etc/nginx/ssl/www.lvjianzhao.top/privkey.pem";
        ssl_session_cache shared:SSL:1m;
        ssl_session_timeout  10m;
        ssl_ciphers HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers on;
        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;
        location / {
	    
        }
        error_page 404 /404.html;
            location = /40x.html {
        }
        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }
}

2.6 訪問測試https是否生效

參考博文:Certbot 自動化生成 https 證書

2.7 設定自動任務,配置自動續訂(防止證書過期)

[root@nginx nginx]# echo "0 0,12 * * * root python -c 'import random; import time; time.sleep(random.random() * 3600)' && certbot renew -q" | tee -a /etc/crontab