1 生成证书
第一步、准备脚本文件
[root@harbor-01 ssl]# vim gencert.sh
#!/usr/bin/env bash
set -eDOMAIN="$1"
IP="$2"
WORK_DIR="$(mktemp -d)"if [ -z "$DOMAIN" ]; thenecho "Domain name needed."exit 1
fiecho "Temporary working dir is $WORK_DIR "
echo "Gernerating cert for $DOMAIN ..."#
# Fix the following error:
# --------------------------
# Cannot write random bytes:
# 139695180550592:error:24070079:random number generator:RAND_write_file:Cannot open file:../crypto/rand/randfile.c:213:Filename=/home/eliu/.rnd
#
[ -f $HOME/.rnd ] || dd if=/dev/urandom of=$HOME/.rnd bs=256 count=1openssl genrsa -out $WORK_DIR/ca.key 4096openssl req -x509 -new -nodes -sha512 -days 3650 \-subj "/C=CN/ST=Beijing/L=Beijing/O=example/OU=Personal/CN=$DOMAIN" \-key $WORK_DIR/ca.key \-out $WORK_DIR/ca.crtopenssl genrsa -out $WORK_DIR/server.key 4096openssl req -sha512 -new \-subj "/C=CN/ST=Beijing/L=Beijing/O=example/OU=Personal/CN=$DOMAIN" \-key $WORK_DIR/server.key \-out $WORK_DIR/server.csrcat > $WORK_DIR/v3.ext <<-EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alt_names[alt_names]
IP.1 = $IP
DNS.1=$DOMAIN
DNS.2=*.$DOMAIN
EOFopenssl x509 -req -sha512 -days 3650 \-extfile $WORK_DIR/v3.ext \-CA $WORK_DIR/ca.crt -CAkey $WORK_DIR/ca.key -CAcreateserial \-in $WORK_DIR/server.csr \-out $WORK_DIR/server.crtopenssl x509 -inform PEM -in $WORK_DIR/server.crt -out $WORK_DIR/$DOMAIN.certmkdir -p ./$DOMAIN
cp $WORK_DIR/server.key $WORK_DIR/server.crt ./$DOMAIN
第二步、假设我们要为 example.com 生成证书,执行如下命令:
[root@harbor-01 ssl]# ./gencert.sh example.com 192.168.136.100注意,申请HTTPS证书时,通常需要提供域名而不是IP地址。但是,有时候确实需要在证书中包含IP地址,否则可能会报错“because it doesn't contain any IP SANs”。生成的后的目录结构如下:
.
├── example.com
│ ├── server.crt
│ └── server.key
└── gencert.sh