自签HTTPS证书

307 阅读1分钟

shell 脚本 gen.sh 文件内容

#! /bin/sh
echo 'make sure server.conf file exist'
echo 'openssl version ...'
echo 'step 0: create root private key ...'
echo 'step 1: create root certificate ...'
echo 'step 2: create server private key ...'
echo 'step 3: create server csr ...'
echo 'step 4: 用根证书颁发证书'

openssl version -a | echo
openssl ecparam -name secp384r1 -genkey -out root.key
openssl req -x509 -new -config root.conf -key root.key -sha384 -days 3650 -out root.crt
openssl ecparam -genkey -name secp384r1 -out server.key
openssl req -new -config server.conf -key server.key -out server.csr -sha384
openssl x509 -req -in server.csr -CA root.crt -CAkey root.key -CAcreateserial -out server.crt -days 3650 -sha384 -extfile v3.ext

echo 'done ...'

根域名证书配置文件内容 root.conf

[ req ]
default_md         = sha384
default_keyfile    = root.key
prompt             = no
# encrypt_key        = 123456
distinguished_name = req_distinguished_name
[ req_distinguished_name ]
countryName = "CN"
localityName = "GZ"
organizationName = "root"
organizationalUnitName = "root"
commonName = "root certificate"
emailAddress = "root@email.com"

服务器域名配置 server.conf

[ req ]
default_bits       = 4096
default_md         = sha384
default_keyfile    = server.key
prompt             = no
distinguished_name = dn
[dn]
C = US
ST = you
L = you
O = you
OU = you
emailAddress = you@email.address
CN = example.com

需要签名的域名配置在 v3.ext 文件

authorityKeyIdentifier = keyid,issuer
basicConstraints = CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = example.com

运行 shell 脚本生成域名证书,根证书 root.crt,域名证书 server.crt

电脑导入根证书,需要重启电脑,使证书生效

nginx.conf 配置

    # HTTPS server
    #
    server {
       listen       443 ssl;
       server_name  localhost;

       ssl_certificate      server.crt;
       ssl_certificate_key  server.key;

       ssl_session_cache    shared:SSL:1m;
       ssl_session_timeout  5m;

       ssl_ciphers  HIGH:!aNULL:!MD5;
       ssl_prefer_server_ciphers  on;

       location / {
           root   html;
           index  index.html index.htm;
       }
    }

重启 nginx $ nginx -s reload

打开 https://localhost