本文为使用过程中的一个工具记录,可实现在本地开启一个 HTTPS 服务器 用于开发或测试。
前面有写过使用 Node.js 搭建 HTTPS 服务器 其中的自签名生成证书方式比较简单,既充当 HTTPS 根证书的角色也充当了用户的角色,本文我们会先创建一个 CA 根证书,再创建一个由 CA 根证书签名的自定义证书。
$ openssl ecparam -out ca.key -name prime256v1 -genkey
$ openssl req -new -sha256 -key ca.key -out ca.csr # 以下为需要输入的交互信息 Country Name (2 letter code) []:CN State or Province Name (full name) []:BeiJing Locality Name (eg, city) []:BeiJing Organization Name (eg, company) []:Node.js Organizational Unit Name (eg, section) []:Node.js Common Name (eg, fully qualified host name) []:test.ca.com Email Address []: Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []:abc123***
$ openssl x509 -req -sha256 -days 365 -in ca.csr -signkey ca.key -out ca.crt
$ openssl ecparam -out server.key -name prime256v1 -genkey
$ openssl req -new -sha256 -key server.key -out server.csr # 注意下面服务器证书的 Common Name 不能与上面颁发者 CA 的 Common Name 一样 Country Name (2 letter code) []:CN State or Province Name (full name) []:ShangHai Locality Name (eg, city) []:ShangHai Organization Name (eg, company) []:Node.js Organizational Unit Name (eg, section) []:Node.js Common Name (eg, fully qualified host name) []:test.https.com Email Address []: Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []:abc123***
$ openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 365 -sha256 # 成功之后有以下提示 Signature ok subject=/C=CN/ST=ShangHai/L=ShangHai/O=Node.js/OU=Node.js/CN=test.https.com Getting CA Private Key 服务端证书中使用到的域名是我们自己定义的,需要在本地 hosts 文件做映射,如果不知道为什么要修改和该如何修改的参考文章 DNS 域名解析过程?github.com/qufei1993/http-protocol/blob/master/docs/dns-process.md 证书文件列表完成之后可以看到如下文件,server.crt 是服务器的证书文件,ca.crt 就是我们创建的根正书。在 Node.js 服务器中配置证书 const express = require('express'); const https = require('https'); const fs = require('fs'); const app = express(); const PORT = 8443; const options = { key: fs.readFileSync('./cert/server.key'), cert: fs.readFileSync('./cert/server.crt') https.createServer(options, app) .listen(PORT, () => console.log(`App listening on port ${PORT}!`));
完成之后可以看到如下文件,server.crt 是服务器的证书文件,ca.crt 就是我们创建的根正书。
const express = require('express'); const https = require('https'); const fs = require('fs'); const app = express(); const PORT = 8443; const options = { key: fs.readFileSync('./cert/server.key'), cert: fs.readFileSync('./cert/server.crt') https.createServer(options, app) .listen(PORT, () => console.log(`App listening on port ${PORT}!`));