2.3. 使用 OpenSSL 为 TLS 服务器证书创建私钥和 CSR
您只有有了来自证书颁发机构(CA)的有效 TLS 证书时才可以使用 TLS 加密的通信频道。要获取证书,您必须首先为您的服务器创建私钥和证书签名请求(CSR)。
流程
在服务器系统上生成私钥,例如:
$ openssl genpkey -algorithm ec -pkeyopt ec_paramgen_curve:P-256 -out <server-private.key>
可选:使用您选择的文本编辑器来准备一个简化创建 CSR 的配置文件,例如:
$ vim <example_server.cnf> [server-cert] keyUsage = critical, digitalSignature, keyEncipherment, keyAgreement extendedKeyUsage = serverAuth subjectAltName = @alt_name [req] distinguished_name = dn prompt = no [dn] C = <US> O = <Example Organization> CN = <server.example.com> [alt_name] DNS.1 = <example.com> DNS.2 = <server.example.com> IP.1 = <192.168.0.1> IP.2 = <::1> IP.3 = <127.0.0.1>
extendedKeyUsage = serverAuth
选项限制证书的使用。使用之前创建的私钥创建 CSR:
$ openssl req -key <server-private.key> -config <example_server.cnf> -new -out <server-cert.csr>
如果省略了
-config
选项,req
工具会提示您额外的信息,例如: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) [XX]: <US> State or Province Name (full name) []: <Washington> Locality Name (eg, city) [Default City]: <Seattle> Organization Name (eg, company) [Default Company Ltd]: <Example Organization> Organizational Unit Name (eg, section) []: Common Name (eg, your name or your server's hostname) []: <server.example.com> Email Address []: <server@example.com>
后续步骤
- 将 CSR 提交给您选择的 CA 进行签名。或者,对于可信网络中的内部使用场景,请使用您的私有 CA 进行签名。如需更多信息,请参阅 第 2.5 节 “使用私有 CA 使用 OpenSSL 为 CSR 发布证书”。
验证
从 CA 获取请求的证书后,检查证书的人类可读部分是否与您的要求匹配,例如:
$ openssl x509 -text -noout -in <server-cert.crt> Certificate: … Issuer: CN = Example CA Validity Not Before: Feb 2 20:27:29 2023 GMT Not After : Feb 2 20:27:29 2024 GMT Subject: C = US, O = Example Organization, CN = server.example.com Subject Public Key Info: Public Key Algorithm: id-ecPublicKey Public-Key: (256 bit) … X509v3 extensions: X509v3 Key Usage: critical Digital Signature, Key Encipherment, Key Agreement X509v3 Extended Key Usage: TLS Web Server Authentication X509v3 Subject Alternative Name: DNS:example.com, DNS:server.example.com, IP Address:192.168.0.1, IP …
其他资源
-
openssl (1)
,x509 (1)
,genpkey (1)
,req (1)
, 和config (5)
man page