openssl双向认证自签名证书生成

发布于:2024-09-05 ⋅ 阅读:(61) ⋅ 点赞:(0)

编写配置文件openssl.cnf

[ req ]
distinguished_name = req_distinguished_name
req_extensions     = req_ext

[ req_distinguished_name ]
countryName            = Country Name (2 letter code)
countryName_default    = US
stateOrProvinceName    = State or Province Name (full name)
stateOrProvinceName_default = California
localityName           = Locality Name (eg, city)
localityName_default   = San Francisco
organizationName       = Organization Name (eg, company)
organizationName_default = YourOrg
organizationalUnitName = Organizational Unit Name (eg, section)
organizationalUnitName_default = YourOrg Unit
commonName             = Common Name (e.g. server FQDN or YOUR name)
commonName_default     = example.com
commonName_max         = 64

[ req_ext ]
subjectAltName = @alt_names

[ alt_names ]
DNS.1 = example.com
DNS.2 = www.example.com
IP.1  = 192.168.1.1

依次执行下面的命令

# 生成 CA 私钥
openssl genrsa -out rootCA.key 2048

# 生成 CA 证书签署请求
openssl req -new -x509 -days 3650 -key rootCA.key -out rootCA.crt -config openssl.cnf

# 生成服务端私钥
openssl genrsa -out server.key 2048

# 生成服务端 CSR
openssl req -new -key server.key -out server.csr -config openssl.cnf

# 生成服务端证书
openssl x509 -req -in server.csr -CA rootCA.crt -CAkey rootCA.key -CAcreateserial -out server.crt -days 3650 -extensions req_ext -extfile openssl.cnf

# 生成客户端私钥
openssl genrsa -out client.key 2048

# 生成客户端 CSR
openssl req -new -key client.key -out client.csr -config openssl.cnf

# 生成客户端证书
openssl x509 -req -in client.csr -CA rootCA.crt -CAkey rootCA.key -CAcreateserial -out client.crt -days 3650 -extensions req_ext -extfile openssl.cnf

查看证书

openssl x509 -in server.crt -text -noout

打包证书

openssl pkcs12 -export -out client.p12 -inkey client.key -in client.crt -certfile rootCA.crt

openssl base64 -in client.p12 -out client.p12.b64

nginx启用双向认证

    sl_certificate /path/to/server.crt;
    ssl_certificate_key /path/to/server.key;
    ssl_client_certificate /path/to/rootCA.crt;   # 用于验证客户端证书的 CA 证书
    ssl_verify_client on;                     # 启用双向认证