2019-08-19 - 自签名证书自动生成脚本

  1. 使用方式, 如需要生成 baidu.com 及子域名的自签名证书,可执行./self_signed_localhost_certificate.sh baidu.com
$ ./self_signed_localhost_certificate.sh baidu.com
Generating a 2048 bit RSA private key
..........................+++
..........+++
writing new private key to 'baidu.com.key'
-----
Signature ok
subject=/C=CA/ST=None/L=NB/O=None/CN=*.baidu.com
Getting Private key

###########################################################################
Done!
###########################################################################
1. To use these files on your server, simply copy both baidu.com.crt and
baidu.com.key to your webserver, and use like so (if nginx, for example)

    ssl_certificate /etc/nginx/ssl/baidu.com.crt;
    ssl_certificate_key /etc/nginx/ssl/baidu.com.key;

2. In browser, export the certificate as an *.cer file,
double click the *.cer to import to the 受信任的根证书颁发机构


$ ll
total 17K
-rw-rw-r--+ 1 DENGBEIQUAN+dengbeiquan DENGBEIQUAN+None 1.4K Aug 19 11:37 baidu.com.crt
-rw-rw-r--+ 1 DENGBEIQUAN+dengbeiquan DENGBEIQUAN+None  968 Aug 19 11:37 baidu.com.csr
-rw-rw-r--+ 1 DENGBEIQUAN+dengbeiquan DENGBEIQUAN+None 1.7K Aug 19 11:37 baidu.com.key
-rwxrwxr-x+ 1 DENGBEIQUAN+dengbeiquan DENGBEIQUAN+None 2.5K Aug 19 11:37 self_signed_localhost_certificate.sh
-rw-rw-r--+ 1 DENGBEIQUAN+dengbeiquan DENGBEIQUAN+None  202 Aug 19 11:37 v3.ext

  1. 浏览器配置
    a. 通过导出成 *.cer 文件
    b. 双击导入到 受信任的根证书颁发机构

  2. 脚本文件

$ cat self_signed_localhost_certificate.sh
#!/usr/bin/env bash
# 参考 https://ningyu1.github.io/site/post/51-ssl-cert/
# 参考 https://stackoverflow.com/questions/7580508/getting-chrome-to-accept-self-signed-localhost-certificate/43666288#43666288

# 配置
DOMAIN=$1                                           # 域名
COMMON_NAME=${2:-*.$1}                              # 通用域名,如输入 baidu.com, 此处为 *.baidu.com
SUBJECT="/C=CA/ST=None/L=NB/O=None/CN=$COMMON_NAME" # 参数
NUM_OF_DAYS=36500                                   # 有效期
V3_EXT_FILE='v3.ext'

# input check
if [ -z "$1" ]; then
    echo "ERROR: Please supply a subdomain to create a certificate for"
    echo "e.g. mysite.com"
    exit 1
fi


# 同时生成 私钥(key) 和 证书请求(csr)
function gen_key_csr() {
    # 通过openssl生成私钥
    # openssl genrsa -out $DOMAIN.key 2048
    # 根据私钥生成证书申请文件csr
    # openssl req -new -key $DOMAIN.key -out $DOMAIN.csr

    # openssl req -new -newkey rsa:2048 -nodes -keyout $DOMAIN.key -out $DOMAIN.csr   # 需手动输入参数
    openssl req -new -newkey rsa:2048 -nodes -keyout $DOMAIN.key -subj "$SUBJECT" -out $DOMAIN.csr # 默认参数
}

# 使用私钥对证书申请进行签名从而生成证书
function gen_cert() {
    openssl x509 -req -in $DOMAIN.csr -out $DOMAIN.crt -signkey $DOMAIN.key -days $NUM_OF_DAYS -sha256 -extfile $V3_EXT_FILE
}

# avoid subject alternative name missing errors
function gen_v3() {
    cat >$V3_EXT_FILE <

你可能感兴趣的:(2019-08-19 - 自签名证书自动生成脚本)