虽然说都8102年了,Let’s Encrypt都支持通配符证书了,但是对我这种不想再去买个域名来给我内网的机器做证书的人来说,用自签名证书当然是最好的方式了。使用OpenSSL做自签名证书的教程网上一搜一把,但是搜出来的那些生成的证书居然都在Firefox下无法通过。究其原因,是没有设置subjectAltName惹的祸。这里给一个生成脚本,让你一键(其实并没有)生成自签名的SSL证书。注意使用前需要修改openssl.cnf文件,删除[ req ]节下的 x509_extensions = v3_ca前面的注释符号,以支持V3版本的证书生成。

输入subjectAltName的时候,可以输入域名或者是IP,但是不要输错了。我就是因为将IP输入到域名区域,导致了firefox不认域名。

#!/bin/bash
echo "自签名证书生成脚本"

read -p "根证书存放位置(不含扩展名): " RootCA
if [ ! -f $RootCA.key ]; then
 echo "$RootCA不存在,将生成一个根证书"
 openssl genrsa -out $RootCA.key
 read -p "根证书过期时间" ExpireDays
 openssl req -new -x509 -key $RootCA.key -out $RootCA.crt -days $ExpireDays
fi

read -p "你要生成的证书名称: " CertCA
if [ ! -f $CertCA.pem ]; then
 echo "$CertCA证书不存在,将生成一个新的证书"
 openssl genrsa -des3 -out $CertCA.pem
 echo "$CertCA私钥不存在,将从证书中解密私钥"
 openssl rsa -in $CertCA.pem -out $CertCA.key
fi

if [ ! -f $CertCA.key ]; then
 echo "$CertCA私钥不存在,您可能需要手工使用下列命令生成"
 echo "openssl rsa -in $CertCA.pem -out $CertCA.key"
fi

echo "为$CertCA生成证书请求文件…"
openssl req -new -key $CertCA.pem -out $CertCA.csr

read -p "DNS名称(subjectAltName)[DNS:localhost, IP:127.0.0.1, ...]" AltName
read -p "根证书过期时间(天): " ExpireDays
openssl x509 -req -days $ExpireDays -CA $RootCA.crt -CAkey $RootCA.key -in $CertCA.csr -out $CertCA.crt -CAcreateserial -extfile <(printf "subjectAltName=$AltName")

if [ -f $CertCA.key ]; then
 cat $CertCA.crt $RootCA.crt > $CertCA.bundle.crt
 echo "生成完毕。你现在可以将$CertCA.bundle.crt与$CertCA.key复制到你的web服务器上了。"
else
 echo "证书生成失败"
 exit 1;
fi
read -p "是否想要显示证书内容?(yes(y)|no(n)): " need
case $need in
 yes|y) 
 openssl x509 -in $CertCA.crt -text -noout 
 ;;
 no|n) 
 #do anything you wannt 
 ;;
 *) 
 #do anything you wannt as default(直接回车)
 openssl x509 -in $CertCA.crt -text -noout 
 ;;
esac

Ref:
[1]StackExchange why-wont-firefox-accept-my-certificate
[2]moxo.io 笔记:OpenSSL 生成「自签名」证书遇到的 missing_subjectAltName 问题

分类: 折腾

6 条评论

fpl · 2020 年 4 月 13 日 上午 10:18

博主,你好。想请教一下,如果我用,自签名ca根证书,就你这种方法的话(因为自签名证书有两种的嘛),我的网站没有域名,如果我IP换了的话,是不是还是要再重新生成证书?

    Jim · 2020 年 4 月 13 日 上午 10:29

    是的

    fpl · 2020 年 4 月 13 日 下午 1:13

    好的 ,谢谢

fpl · 2020 年 4 月 11 日 下午 8:19

博主好,这个脚本生成的是自签名带ca的证书吗?

    Jim · 2020 年 4 月 12 日 下午 8:24

    是的。会先生成一个CA,然后再用这个CA去生成证书。

      fpl · 2020 年 4 月 13 日 上午 10:14

      哦哦 好的 谢谢博主

回复 Jim 取消回复

Avatar placeholder

您的电子邮箱地址不会被公开。 必填项已用*标注