且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用openSSL构造一个支持https的nodejs服务器

更新时间:2022-08-12 23:26:55

首先通过下面的链接下载openSSL

https://slproweb.com/products/Win32OpenSSL.html


下载完毕后,执行openssl进入交互式界面:



使用命令生成privatekey.pem 1024意思是1024位长度。


openssl genrsa -out privatekey.pem 1024



生成的privatekey.pem,打开看一看长啥样:




什么是pem文件?


.pem - Defined in RFCs 1421 through 1424, this is a container format that may include just the public certificate (such as with Apache installs, and CA certificate files /etc/ssl/certs), or may include an entire certificate chain including public key, private key, and root certificates. Confusingly, it may also encode a CSR (e.g. as used here) as the PKCS10 format can be translated into PEM. The name is from Privacy Enhanced Mail (PEM), a failed method for secure email but the container format it used lives on, and is a base64 translation of the x509 ASN.1 keys.


简单的说,就是一个密钥文件。


第二步,基于第一步生成的密钥文件生成一个证书请求:

openssl req -new -key privatekey.pem -out certrequest.csr



如果懒得维护证书明细,直接敲回车,会自动填入默认值:



最后基于第一步生成的密钥和证书请求生成一个数字证书:当然颁发机构就是自己了,仅用于测试目的。

openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out certificate.pem



至此我们有了privatekey.pem和Certificate.pem两个证书了。


下面是我https服务器的代码,很简单,只有50几行:

使用openSSL构造一个支持https的nodejs服务器使用openSSL构造一个支持https的nodejs服务器从代码里不难理解这两个pem文件是如何用在https服务器里的。

最后在浏览器里测试。因为是自己颁发的证书,没有经过CA验证,所以浏览器会显示一个警告。