OpenSSL自签名SSL证书相关脚本

Posted 博​唯

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了OpenSSL自签名SSL证书相关脚本相关的知识,希望对你有一定的参考价值。

本文介绍的OpenSSL脚本

  • 采用自签名CA,以方便多份证书的签发和使用
  • 支持SAN(主体备用名称)
  • 包含各种文件格式的导出脚本,并简述文件用法

1. RSA证书

创建目录结构

mkdir ssl
cd ssl
mkdir certs private csr conf

# intial directory structure
# ssl/
# ├── certs/
# ├── conf/
# │   ├── ca.conf
# │   └── localhost.conf
# ├── csr/
# └── private/

解释扩展名

Notes on file extensions
*.crt - PEM-encded single certificate or multiple certificates
  *-cert.crt signed certificate (-----CERTIFICATE-----)
  *-chain.crt list of certificates from intermediates to root
*.key - PEM-encoded private key
  *-rsa.key PKCS#1 (-----RSA PRIVATE KEY-----)
  *.key PKCS#8 (-----PRIVATE KEY-----) or SEC1 (-----EC PRIVATE KEY-----)
*.jks - JKS kind of Java keystore (certificate + private key)
*.jts - JKS-type truststore (certificates)
*-cert.p12 - PKCS12-type keystore (certificate + private key)
*-chain.p12 - PKCS12-type truststore (certificates)
*.pfx - PKCS12-type Microsoft PFX

准备配置文件conf/ca.conf以创建CA

[ req ]
default_bits        = 2048
default_keyfile     = private/ca-encrypted.key
distinguished_name  = subject
req_extensions      = req_ext
x509_extensions     = v3_ca

# The Subject DN can be formed using X501 or RFC 4514 (see RFC 4519 for a description).
#   Its sort of a mashup. For example, RFC 4514 does not provide emailAddress.
[ subject ]
# Country Name (2 letter code)
C=CN
# State or Province Name (full name)
ST=BJ
# Locality Name (eg, city)
L=Beijing
# Organization Name (eg, company)
O=WebDev Org
# Organization Unit (eg, department, sub-company, job-type, regions)
OU=IT Dept
# Common Name (e.g. server FQDN or Authority Name)
CN=WebDev CA

[ req_ext ]

subjectKeyIdentifier        = hash
basicConstraints            = CA:TRUE
keyUsage                    = digitalSignature, keyEncipherment
extendedKeyUsage            = serverAuth, clientAuth, codeSigning

[ v3_ca ]

basicConstraints        = critical,CA:TRUE
subjectKeyIdentifier    = hash
authorityKeyIdentifier  = keyid:always, issuer:always
keyUsage                = critical, cRLSign, digitalSignature, keyCertSign
#subjectAltName          = @alt_ica
extendedKeyUsage        = clientAuth, serverAuth, codeSigning

创建CA

#
# create CA
#
# 1. generate a rsa key for CA
openssl genrsa -aes256 -out private/ca-rsa.key 2048

# 2. convert private key from PKCS#1 to PKCS#8
openssl pkcs8 -topk8 -inform PEM -in private/ca-rsa.key -outform PEM -out private/ca-encrypted.key

# 3. create ca certificate
openssl req -new -config conf/ca.conf \\
  -subj "/C=CN/ST=BJ/L=Beijing/O=Web Dev Org/OU=IT Dept/CN=WebDev CA" \\
  -x509 -sha256 -days 3650 -key private/ca-encrypted.key -out certs/ca.crt

创建证书签名请求

#
# create certificate signing request
#
# the domain name (e.g. example.com)
domain=localhost

# 1. create a server rsa key
openssl genrsa -out private/$domain-rsa.key 2048

# 2. convert rsa key to pkcs8 key (without password protection)
openssl pkcs8 -topk8 -nocrypt -inform PEM -in private/$domain-rsa.key -outform PEM -out private/$domain.key

# 3. create a server certificate request
openssl req -new -sha256 \\
  -subj "/C=CN/ST=BJ/L=Beijing/O=Web Dev Org/OU=IT Dept/CN=localhost" \\
  -key private/$domain.key \\
  -out csr/$domain.csr

准备配置文件conf/localhost.conf以签发证书请求

[ x509_extensions ]

subjectKeyIdentifier      = hash
authorityKeyIdentifier    = keyid,issuer
basicConstraints          = CA:FALSE
keyUsage                  = digitalSignature
subjectAltName            = @alternate_names
extendedKeyUsage          = serverAuth,clientAuth


[ alternate_names ]
DNS.1       = localhost
DNS.2       = loopback
IP.1        = 127.0.0.1
IP.2       = 127.0.1.1

签发证书请求

#
# sign a certificate request
#
# the domain name (e.g. localhost)
domain=localhost

# 1. sign a certificate
openssl x509 -req \\
  -days 730 \\
  -in csr/$domain.csr \\
  -CA certs/ca.crt -CAkey private/ca-encrypted.key -CAserial certs/ca.srl -CAcreateserial \\
  -extfile conf/$domain.conf -extensions x509_extensions \\
  -out certs/$domain-cert.crt

#
# test certificate with SSLServer and SSLClient
#
# on one tty window
openssl s_server -accept 1443 -www -key private/$domain.key -cert certs/$domain-cert.crt

# on another tty window
openssl s_client -showcerts -connect $domain:1443 -CAfile certs/ca.crt

导出各种HTTP服务端所需格式

#
# export for HTTP Servers
#
# create certificate chain (for Apache / Tomcat / Node.js)
cp certs/ca.crt certs/$domain-chain.crt

# create self_plus_intermediates_plus_root (for nginx)
cat certs/$domain-cert.crt <(echo) certs/$domain-chain.crt > certs/$domain.crt

# create java keystore in PKCS12 (for Java 9+, Java 8)
openssl pkcs12 -export -in certs/$domain-cert.crt -inkey private/$domain.key -name "$domain" -out certs/$domain-cert.pfx
$JAVA_HOME/bin/keytool -importkeystore -srcstoretype PKCS12 -srckeystore certs/$domain-cert.pfx \\
  -alias "$domain" -deststoretype PKCS12 -destkeystore certs/$domain-cert.p12
$JAVA_HOME/bin/keytool -importkeystore -srcstoretype PKCS12 -srckeystore certs/$domain-cert.pfx \\
  -alias "$domain" -deststoretype JKS -destkeystore certs/$domain-cert.jks

导出各种HTTP客户端所需格式

#
# export for HTTP Clients
#
# create PKCS12 truststore (for Windows)
openssl pkcs12 -export -in certs/ca.crt -nokeys -name "WebDev CA" -out certs/ca.pfx
# create PKCS12 truststore (for Java 9+, Java 8)
$JAVA_HOME/bin/keytool -importcert -file certs/ca.crt -alias "WebDev CA" -storetype PKCS12 -keystore certs/$domain-chain.p12 -noprompt
$JAVA_HOME/bin/keytool -importcert -file certs/ca.crt -alias "WebDev CA" -storetype JKS -keystore certs/$domain-chain.jts -noprompt
# append this CA to ca bundle (for Postman)
cat certs/ca.crt <(echo) >> certs/ca-certs.crt

2. 已签发证书的用法(用于服务端)

配置Nginx,在nginx.conf中使用

ssl_certificate /etc/nginx/ssl/certs/localhost.crt;
ssl_certificate_key /etc/nginx/ssl/private/localhost.key;

配置Tomcat 8.5+,在server.xml中使用

<SSLHostConfig>
  <Certificate certificateKeyFile="/etc/nginx/ssl/private/localhost.key"
      certificateFile="/etc/nginx/ssl/certs/localhost-cert.crt"
      certificateChainFile="/etc/nginx/ssl/certs/localhost-chain.crt"
      type="RSA" />
</SSLHostConfig>
<!-- or -->
<SSLHostConfig truststoreFile="/etc/nginx/ssl/certs/localhost-chain.jts"
    truststorePassword="changeit"
    truststoreType="JKS">
  <Certificate 
      certificateKeystoreFile="/etc/nginx/ssl/certs/localhost-cert.jks"
      certificateKeystorePassword="changeit"
      certificateKeystoreType="JKS"
      certificateKeyAlias="localhost"
      type="RSA" />
</SSLHostConfig>
<!-- or -->
<SSLHostConfig truststoreFile="/etc/nginx/ssl/certs/localhost-chain.p12"
    truststorePassword="changeit"
    truststoreType="PKCS12">
  <Certificate 
      certificateKeystoreFile="/etc/nginx/ssl/certs/localhost-cert.p12"
      certificateKeystorePassword="changeit"
      certificateKeystoreType="PKCS12"
      certificateKeyAlias="localhost"
      type="RSA" />
</SSLHostConfig>

编写Node.js HTTP服务脚本,在server.js中使用

let server=https.createServer({
  key: fs.readFileSync("/etc/nginx/ssl/private/localhost.key"),
  cert: fs.readFileSync("/etc/nginx/ssl/certs/localhost-cert.crt"),
  ca: fs.readFileSync("/etc/nginx/ssl/certs/localhost-chain.crt"),
});

配置webpack-dev-server,在webpack.config.js中使用

module.exports = {
  devServer: {
    https: {
      key: '/etc/nginx/ssl/private/localhost.key',
      cert: '/etc/nginx/ssl/certs/localhost-cert.crt',
      ca: '/etc/nginx/ssl/certs/localhost-chain.crt',
    },
  },
};

3. 自签名CA证书的用法(用于客户端)

导入到Windows

双击CA证书certs/ca.pfx,安装证书(存储位置为"本地计算机",证书存储为"受信任的根证书颁发机构")。
导入后适用于 IE、Edge及其WebView、Chrome、基于其他Chromium的浏览器等等

导入到Firefox

注:如果已经将自签名CA证书certs/ca.pfx导入到Windows,那么可通过访问about:config设置security.enterprise_roots.enabledtrue来共享Windows受信任的根证书而无需再Firefox单独导入
在Firefox Settings / Certificates / View Certificates / 导入文件certs/ca.pfx到"Your Certificates"

导入到Postman

在Postman Settings / Certificates / CA Certificates指定合并的CA合辑文件/etc/nginx/ssl/certs/ca-certs.crt

导入到Java HTTP客户端

设置JVM 启动参数,如-Djavax.net.ssl.trustStore=/etc/nginx/ssl/certs/localhost-chain.jts -Djavax.net.ssl.trustStorePassword=changeit -Djavax.net.ssl.trustStoreType=JKS,对于Java9+也可换成-Djavax.net.ssl.trustStore=/etc/nginx/ssl/certs/localhost-chain.p12 -Djavax.net.ssl.trustStorePassword=changeit -Djavax.net.ssl.trustStoreType=PKCS12

导入到Node.js HTTP客户端

在运行node之前,先设置进程范围的环境变量NODE_EXTRA_CA_CERTS,如env NODE_EXTRA_CA_CERTS=/etc/nginx/ssl/certs/ca-certs.crt node XXX.js(若要兼容Windows,则请npm install -D cross-env并把env改成cross-env

4. 附: EC证书

准备配置文件conf/example.com.conf以签发证书

[ x509_extensions ]

subjectKeyIdentifier      = hash
authorityKeyIdentifier    = keyid,issuer
basicConstraints          = CA:FALSE
keyUsage                  = digitalSignature
subjectAltName            = @alternate_names
extendedKeyUsage          = serverAuth, clientAuth


[ alternate_names ]

DNS.1       = example.com
DNS.2       = *.example.com

EC证书的申请、签发和转换

#
# create EC CA
#
# find curve with `openssl ecparam -list_curves`

# generate a private key for a curve
openssl ecparam -genkey -name prime256v1 -noout -out private/ca-ec.key

# generate a encrypted edition of the private key 
openssl ec -aes256 -in private/ca-ec.key -out private/ca-ec-encrypted.key

# create ca certificate
openssl req -new -config conf/ca.conf \\
  -subj "/C=CN/ST=BJ/L=Beijing/O=Web Dev Org/OU=IT Dept/CN=WebDev ECC CA" \\
  -x509 -sha256 -days 3650 -key private/ca-ec-encrypted.key -out certs/ca-ec.crt




#
# create certificate aigning request
#
# the domain name (e.g. example.com)
domain=foo.apps.example.com

# generate a private key
openssl ecparam -genkey -name prime256v1 -out private/$domain.key

# create a certificate signing request
openssl req -new \\
  -subj "/C=CN/ST=BJ/L=Beijing/O=Web Dev Org/OU=IT Dept/CN=$domain" \\
  -key private/$domain.key \\
  -out csr/$domain.csr

# optionally, generate corresponding public key
openssl ec -in private/$domain.key -pubout -out public/$domain.pub




#
# sign for certificate request
#
# the domain name (e.g. example.com)
domain=example.com

openssl x509 -req \\
  -sha256 -days 730 \\
  -in csr/$domain.csr \\
  -CA certs/ca-ec.crt -CAkey private/ca-ec-encrypted.key -CAserial certs/ca-ec.srl -CAcreateserial  \\
  -extfile conf/$domain.conf -extensions x509_extensions \\
  -out certs/$domain-cert.crt



#
# export for HTTP Servers
#
# create certificate chain (for Apache, Tomcat, Node.js)
cp certs/ca-ec.crt certs/$domain-chain.crt

# for Nginx
cat certs/$domain-cert.crt <(echo) certs/ca-ec.crt > certs/$domain.crt

#
# export for HTTP Clients
#
# create PKCS12 truststore (for Windows, Firefox)
openssl pkcs12 -export -in certs/ca-ec.crt -nokeys -out certs/ca-ec.pfx

# append this CA to ca bundle (for Postman)
cat certs/ca-ec.crt <(echo) >> certs/ca-certs.crt

EC证书在服务端的配置方式,与RSA证书的基本一样,除了在Tomcat配置SSL时指定type,如
<Certificate ... type="EC" />

附注:

  • 上述脚本中:CA key文件采用密码保护是为了防止key文件意外泄露后被滥用,server key文件不采用密码保护是为了避免密码暴露在各服务器的配置文件中(PKCS12的除外,因其密码必填)。
  • 关于命令keytool,建议保证keytool所在的JDK与目标运行环境的JDK厂商匹配,且大版本匹配。因为我测出一个问题:OpenJDK 17 for Linux的keytool创建的p12文件,Oracle JDK 11 for Windows不认而报奇怪的错误。

以上是关于OpenSSL自签名SSL证书相关脚本的主要内容,如果未能解决你的问题,请参考以下文章

openssl 自签名证书 - 安装openssl(一)

openssl使用多种方法签名自签名

OpenSSL生成HTTPS自签名证书

什么是自签名SSL证书?

如何创建一个自签名的SSL证书

用openssl生成的ssl证书和付费的有啥区别