美文网首页
node启一个https服务

node启一个https服务

作者: 溪离欣洛 | 来源:发表于2017-03-12 18:24 被阅读278次

    首先,我们需要一个私钥。

    ➜  https  openssl genrsa -out privatekey.pem 1024
    Generating RSA private key, 1024 bit long modulus
    ...........................++++++
    ..........................++++++
    e is 65537 (0x10001)
    

    之后用该私钥生成一个证书,按照提示 输入国家缩写等信息 需要注意的是 common Name需要填写 认证的域名。

    ➜  https  openssl req -new -key privatekey.pem -out certrequest.csr
    You are about to be asked to enter information that will be incorporated
    into your certificate request.
    What you are about to enter is what is called a Distinguished Name or a DN.
    There are quite a few fields but you can leave some blank
    For some fields there will be a default value,
    If you enter '.', the field will be left blank.
    -----
    Country Name (2 letter code) [AU]:CN
    State or Province Name (full name) [Some-State]:beijing
    Locality Name (eg, city) []:neijing
    Organization Name (eg, company) [Internet Widgits Pty Ltd]:qunar
    Organizational Unit Name (eg, section) []:qunar
    Common Name (e.g. server FQDN or YOUR name) []:eva.li.qunar.com
    Email Address []:xilixinluo@gmail.com
    
    Please enter the following 'extra' attributes
    to be sent with your certificate request
    A challenge password []:eva.li
    An optional company name []:qunar
    

    之后对私钥和证书进行自签名的认证

    ➜  https  openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out certificate.pem
    Signature ok
    subject=/C=CN/ST=beijing/L=neijing/O=qunar/OU=qunar/CN=eva.li.qunar.com/emailAddress=xilixinluo@gmail.com
    Getting Private key
    

    到此为止我们需要的三个基础文件已经准备就绪,之后就是用https模块起一个node服务。

    var https = require('https')
        ,fs = require("fs");
    
    var options = {
        key: fs.readFileSync('./privatekey.pem'),
        cert: fs.readFileSync('./certificate.pem'),
        ca: fs.readFileSync('./certrequest.pem')
    };
    
    https.createServer(options, function(req,res){
        res.writeHead(200, {
            'Content-type' : 'text/html'
        });
        res.write('<h1>HTTPS server</h1>');
        res.end('<p>Hello baby!</p>');
    }).listen(8888);
    

    这时我们起服务的时候Chrome浏览器中显示不安全提醒,这是因为浏览器没有ca认证的证书。这时需要我们手动拷贝生成好的证书到系统中即可,如下图所示。

    Paste_Image.png Paste_Image.png

    这样再会刷新页面,页面就已经是验证通过的状态了。

    Paste_Image.png

    相关文章

      网友评论

          本文标题: node启一个https服务

          本文链接:https://www.haomeiwen.com/subject/zycxnttx.html