使用命令行脚本生成自签名证书
最常见和通用的做法便是安装配置一个带有 openssl 环境的系统,然后使用命令行执行类似下面这样的命令:
```
openssl req -x509 -newkey rsa:2048 -keyout ssl/${fileName}.key -out ssl/${fileName}.crt -days 3600 -nodes ...
```
这里如果你选择不使用配置文件的话,得参考openssl 文档,附带一堆参数,或需要交互式的输入一堆选项,并祈祷在中间每一步没有输入出错,例如下面这样:
```
enerating a RSA private key
....................................................................................................................................................................................................................................................................++++
.............................................................++++
writing new private key to 'example.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:CN
State or Province Name (full name) [Some-State]:XX
Locality Name (eg, city) []:XXXX
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Example, Inc
Organizational Unit Name (eg, section) []:IT
Common Name (e.g. server FQDN or YOUR name) []:example.com
Email Address []:example@soulteary.com
```
相比之下,使用类似下面的配置生成证书会稍微容易那么一些:
```
#!/bin/sh
mkdir -p ssl
OUTPUT_FILENAME="example.com"
printf "[req]
prompt = no
default_bits = 4096
default_md = sha256
encrypt_key = no
string_mask = utf8only
distinguished_name = cert_distinguished_name
req_extensions = req_x509v3_extensions
x509_extensions = req_x509v3_extensions
[ cert_distinguished_name ]
C = CN
ST = BJ
L = BJ
O = example.com
OU = example.com
CN = example.com
[req_x509v3_extensions]
basicConstraints = critical,CA:true
subjectKeyIdentifier = hash
keyUsage = critical,digitalSignature,keyCertSign,cRLSign #,keyEncipherment
extendedKeyUsage = critical,serverAuth #, clientAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = example.com
DNS.2 = *.example.com
">ssl/${OUTPUT_FILENAME}.conf
openssl req -x509 -newkey rsa:2048 -keyout ssl/$OUTPUT_FILENAME.key -out ssl/$OUTPUT_FILENAME.crt -days 3600 -nodes -config ssl/${OUTPUT_FILENAME}.conf
```
类似的脚本,我曾在 Traefik 示例脚本中提到过: https://github.com/soulteary/traefik-example/blob/main/scripts/generate-certs.sh 。