Tekkaman

导航

 

NodeJS搭建HTTPS服务器

1、创建服务端证书。

openssl genrsa -out server-key.pem 1024
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

  服务器代码:

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');

 

2、创建客户端证书。

openssl genrsa -out client-key.pem
openssl req -new -key client-key.pem -out client-csr.pem
openssl x509 -req -CA ca-cert.pem -CAkey ca-key.pem -CAcreateserial -in client-csr.pem -out client-cert.pem

  客户端代码:

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

var options = {
    hostname:'127.0.0.1',
    port:3000,
    path:'/',
    method:'GET',
    key:fs.readFileSync('./keys/client-key.pem'),
    cert:fs.readFileSync('./keys/client-cert.pem'),
    ca: [fs.readFileSync('./keys/ca-cert.pem')],
    agent:false
};

options.agent = new https.Agent(options);
var req = https.request(options,function(res){
console.log("statusCode: ", res.statusCode);
  console.log("headers: ", res.headers);
    res.setEncoding('utf-8');
    res.on('data',function(d){
        console.log(d);
    })
});

req.end();

req.on('error',function(e){
    console.log(e);
})

 

参考:

1、http://cnodejs.org/topic/54745ac22804a0997d38b32d

posted on 2017-01-03 18:44  Tekkaman  阅读(329)  评论(0编辑  收藏  举报