通过OpenSSL创建证书文件构建https服务

前言

以前用node.js构建过https服务,很简单,就是把两个文件的路径放在代码里,把http协议换成https就搞定了。不过今天我收到的是一个文件夹,两个文件怎么用都报错,于是有了自己生成证书文件来证实问题出在哪里的想法。最后发现问题在于这个文件夹里全是—–BEGIN CERTIFICATE—–的文件,找不到一个—–BEGIN RSA PRIVATE KEY—–的文件。

OpenSSL生成证书

  • 创建openssl.cnf文件

    1
    [req]  
        distinguished_name = req_distinguished_name  
        req_extensions = v3_req  
      
        [req_distinguished_name]  
        countryName = Country Name (2 letter code)  
        countryName_default = CN  
        stateOrProvinceName = State or Province Name (full name)  
        stateOrProvinceName_default = BeiJing  
        localityName = Locality Name (eg, city)  
        localityName_default = YaYunCun  
        organizationalUnitName  = Organizational Unit Name (eg, section)  
        organizationalUnitName_default  = Domain Control Validated  
        commonName = Internet Widgits Ltd  
        commonName_max  = 64  
      
        [ v3_req ]  
        # Extensions to add to a certificate request  
        basicConstraints = CA:FALSE  
        keyUsage = nonRepudiation, digitalSignature, keyEncipherment  
        subjectAltName = @alt_names  
      
        [alt_names]  
    	#注意这个IP.1的设置,IP地址需要和你的服务器的监听地址一样
        IP.1 = 127.0.0.1
  • 为CA生成私钥

    1
    openssl genrsa -out ca-key.pem -des 1024
  • 通过CA私钥生成CSR

    1
    openssl req -new -key ca-key.pem -out ca-csr.pem
  • 通过CSR文件和私钥生成CA证书

    1
    openssl x509 -req -in ca-csr.pem -signkey ca-key.pem -out ca-cert.pem
  • 通过服务器私钥文件和CSR文件生成服务器证书

    1
    openssl x509 -req -CA ca-cert.pem -CAkey ca-key.pem -CAcreateserial -in server-csr.pem -out server-cert.pem -extensions v3_req -extfile openssl.cnf

node.js服务端

1
var https = require('https');
var fs = require('fs');

var options = {
	key: fs.readFileSync('./keys/server-key.pem'),
	// ca: [fs.readFileSync('./keys/ca-cert.pem')],
	cert: fs.readFileSync('./keys/server-cert.pem')
};

https.createServer(options,function(req,res){
	res.writeHead(200);
	res.end('hello world\n');
}).listen(3000,'127.0.0.1');

参考文献

https://cnodejs.org/topic/54745ac22804a0997d38b32d

文章目录
  1. 1. 前言
  2. 2. OpenSSL生成证书
  3. 3. node.js服务端
  4. 4. 参考文献
,