用Node.js创建自签名的HTTPS服务器

2018-06-29  本文已影响0人  Veb

https搭建服务器时,需要证书,接下来,一块了解一下证书生成!

首先打开cmd,输入openssl命令,如果可以正常访问,则可继续以下操作,否则,去自行下载openssl工具。


具体操作流程分为:

  1. 创建自己的CA机构
  2. 创建服务器端证书

创建自己的CA机构

openssl genrsa -out ssl.key 2048
openssl req -new -key ssl.key -out ca-csr.pem
openssl x509 -req -in ca-csr.pem -signkey ssl.key -out ca-cert.pem

创建服务器端证书

openssl genrsa -out server-key.pem 1024

在当前目录下创建openssl.cnf文件,将以下内容放入:

[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
openssl req -new -key server-key.pem -config openssl.cnf -out server-csr.pem

一路回车。

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

一路回车。

HTTPS 服务器代码

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');
上一篇下一篇

猜你喜欢

热点阅读