详细介绍了使用 OpenSSL 生成自签名 CA 证书以及签发带 SAN 扩展的服务器证书的完整流程。

自建CA使用SAN签发证书
3 mins
543 words
Loading views

CA 证书生成h2

创建 CA 配置文件h3

首先,创建用于生成根 CA 的配置文件:

Terminal window
cat > ca.conf << EOF
[ req ]
default_bits = 2048
default_md = sha256
prompt = no
encrypt_key = no
distinguished_name = dn
[ dn ]
C = CN
ST = Beijing
L = Beijing
O = Dev
OU = Dev Root CA
CN = Dev Root CA
emailAddress = admin@example.com
EOF

生成 CA 证书h3

执行以下命令生成 CA 私钥和根证书:

Terminal window
# 生成 CA 私钥(使用 prime256v1 椭圆曲线)
openssl ecparam -out ca.key -name prime256v1 -genkey
# 生成证书签名请求(CSR)
openssl req -new -sha256 -key ca.key -out ca.csr -config ca.conf
# 使用私钥自签名生成根证书,有效期 10 年
openssl x509 -req -sha256 -days 3650 -in ca.csr -signkey ca.key -out ca.crt

签发 SAN 证书h2

创建证书配置文件h3

创建包含 Subject Alternative Name (SAN) 扩展的证书配置文件:

Terminal window
cat > domain.conf << EOF
[ req ]
default_bits = 2048
default_md = sha256
prompt = no
encrypt_key = no
distinguished_name = dn
req_extensions = v3_req
[ dn ]
C = CN
ST = Beijing
L = Beijing
O = Organization
OU = Dev Team
CN = example.com
emailAddress = admin@example.com
[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = example.com
DNS.2 = *.example.com
EOF

签发证书h3

使用前面创建的 CA 签发 SAN 证书:

Terminal window
# 生成域名私钥和 CSR
openssl genrsa -out example.com.key 2048
openssl req -new -nodes -key example.com.key -out example.com.csr -config domain.conf
# 使用 CA 签发证书(有效期 10 年)
openssl x509 -req -in example.com.csr \
-CA ca.crt -CAkey ca.key -CAcreateserial \
-out example.com.crt -days 3650 -sha256 \
-extensions v3_req -extfile domain.conf
# 验证生成的证书信息
openssl x509 -in example.com.crt -text -noout

补全完整的证书链h3

将服务器证书和 CA 证书合并,形成完整的证书链文件:

Terminal window
cat example.com.crt ca.crt > example.com.fullchain.crt

文件说明h2

  • ca.conf: CA 的配置文件,定义了生成根证书时使用的参数。
  • ca.key: CA 的私钥文件,需严格保密。
  • ca.crt: 自签名的根证书,用于签发后续的服务器证书。
  • domain.conf: 签发服务器证书时的配置文件,定义了 SAN 等扩展信息。
  • example.com.key: 服务器证书对应的私钥。
  • example.com.csr: 证书签名请求文件,包含了申请证书的公钥和主体信息。
  • example.com.crt: 由 CA 签发的服务器证书。
  • example.com.fullchain.crt: 完整的证书链文件,包含服务器证书和 CA 证书。