自签证书

记录一下用 openssl 自签证书的步骤。大部分内容参考了这篇博文

CA

公钥

sh
openssl genrsa -des3 -out ca.key 4096
-des3
  These options encrypt the private key with
  specified cipher before outputting it. If none
  of these options is specified no encryption is
  used. If encryption is used a pass phrase is
  prompted for if it is not supplied via the
  -passout argument.
numbits
  The size of the private key to generate in
  bits. This must  be the last option specified.
  The default is 2048 and values less than 512
  are not allowed.

证书

sh
openssl req -new -x509 -days 120 -key ca.key -out ca.crt
-days n
  When -x509 is in use this specifies the number
  of days to certify the certificate for,
  otherwise it is ignored. n should be a
  positive integer. The default is 30 days.

注:可以用以下命令查看证书信息:

sh
openssl x509 -in ca.crt -text -noout

服务器

私钥

同上

sh
openssl genrsa -out server.key 4096

证书

证书请求

sh
openssl req -new -key server.key -out server.csr

签发证书

sh
openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -set_serial 01 -days 120 -out server.crt
-set_serial n
  Specifies the serial number to use. This
  option can be used with the -key,  -signkey,
  or -CA options. If used in conjunction with
  the -CA option the serial number file (as
  specified by the -CAserial option) is not
  used.

  The serial number can be decimal or hex (if
  preceded by "0x").

注:可以用以下命令验证证书:

sh
openssl verify -verbose -CAfile ca.crt server.crt
SAN

注:本节参考了这个 gist

如果自签证书要在浏览器内使用,那么需要在证书里包括 Subject Alternative Name (SAN)。大多数现代浏览器不再信任没有指定 SAN 的证书。

要在证书里指定 SAN,需要在签发证书前创建一个文件 v3.ext:

subjectKeyIdentifier   = hash
authorityKeyIdentifier = keyid:always,issuer:always
basicConstraints       = CA:TRUE
keyUsage               = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment, keyAgreement, keyCertSign
subjectAltName         = DNS:example.com, DNS:*.example.com
issuerAltName          = issuer:copy

将行5内的域名替换为合适的内容。

然后在从证书请求签发证书时,在命令中添加 -extfile v3.ext

在 Windows 上导入 CA 证书

运行 certmgr.msc,选择导入,根据向导提示选择证书文件。