使用openSSL構造一個支持https的nodejs服務器

首先經過下面的連接下載openSSL https://slproweb.com/products/Win32OpenSSL.htmlhtml

下載完畢後,執行openssl進入交互式界面: web

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

openssl genrsa -out privatekey.pem 1024express

生成的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.app

簡單的說,就是一個密鑰文件。socket

第二步,基於第一步生成的密鑰文件生成一個證書請求: openssl req -new -key privatekey.pem -out certrequest.csr測試

若是懶得維護證書明細,直接敲回車,會自動填入默認值:ui

最後基於第一步生成的密鑰和證書請求生成一個數字證書:固然頒發機構就是本身了,僅用於測試目的。 openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out certificate.pem

至此咱們有了privatekey.pem和Certificate.pem兩個證書了。

下面是我https服務器的代碼,很簡單,只有50幾行:

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

var httpOptions =  {
 key: fs.readFileSync("keys/privatekey.pem"),
 cert: fs.readFileSync("keys/certificate.pem")
}

var server = https.createServer(httpOptions, app);
var io = require('socket.io')(server);

console.log("https server listens on port 8080...");

server.listen(8080);

function print_env(){
  console.log(process.env);
}

app.get('/', function (req, res) {

  var response = "Hello World";
  res.send(response);
});

app.get('/env', function (req, res) {

  print_env();
  // res.sendFile(__dirname + '/index.html');
  var response = JSON.stringify(process.env);
  res.send(response);
});

app.get('/redis', function (req, res) {

  var redisClient = require("./redisClient");
  
  function callback(response){
    // var response = "ok";//JSON.stringify(process.env);
    res.send(response);
  }
  redisClient.test(callback);
});

io.on('connection', function (socket) {
  console.log("connect comming from client: " + socket.id);
  socket.emit('messages_jerry', { hello: 'world greeting from Server!' });
  socket.on('messages', function (data) {
    console.log("data received from Client:" + JSON.stringify(data,2,2));
  });
});

從代碼裏不難理解這兩個pem文件是如何用在https服務器裏的。 最後在瀏覽器裏測試。由於是本身頒發的證書,沒有通過CA驗證,因此瀏覽器會顯示一個警告。

要獲取更多Jerry的原創文章,請關注公衆號"汪子熙":

相關文章
相關標籤/搜索