TLS 套接字服务器和客户端

此常规 TCP 连接与常规 TCP 连接之间的唯一主要区别是私钥和公共证书,你必须将其设置为选项对象。

如何创建密钥和证书

此安全过程的第一步是创建私钥。什么是私钥?基本上,它是一组用于加密信息的随机噪声。从理论上讲,你可以创建一个密钥,并使用它来加密你想要的任何密钥。但最佳做法是为特定事物设置不同的密钥。因为如果有人偷了你的私钥,那就像是有人偷了你的房门键。想象一下,如果你使用相同的键来锁定你的车,车库,办公室等。

openssl genrsa -out private-key.pem 1024

一旦我们拥有了私钥,我们就可以创建一个 CSR(证书签名请求),这是我们要求由一个花哨的权威机构签署私钥的请求。这就是你必须输入与贵公司相关的信息的原因。签名机构将查看此信息,并用于验证你。在我们的例子中,你键入的内容并不重要,因为在下一步我们将自己签署我们的证书。

openssl req -new -key private-key.pem -out csr.pem

现在我们已经完成了我们的论文工作,现在是时候假装我们是一个很酷的签名机构。

openssl x509 -req -in csr.pem -signkey private-key.pem -out public-cert.pem

现在你拥有了私钥和公共证书,你可以在两个 NodeJS 应用程序之间建立安全连接。而且,正如你在示例代码中看到的那样,这是一个非常简单的过程。

重要!

自从我们自己创建公共证书以来,我们的证书毫无价值,因为我们是无名小卒。默认情况下,NodeJS 服务器不会信任这样的证书,这就是为什么我们需要告诉它实际信任我们的证书,并使用以下选项 rejectUnauthorized:false。非常重要 :永远不要在生产环境中将此变量设置为 true。

TLS 套接字服务器

'use strict';

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

const PORT = 1337;
const HOST = '127.0.0.1'

var options = {
    key: fs.readFileSync('private-key.pem'),
    cert: fs.readFileSync('public-cert.pem')
};

var server = tls.createServer(options, function(socket) {

    // Send a friendly message
    socket.write("I am the server sending you a message.");

    // Print the data that we received
    socket.on('data', function(data) {

        console.log('Received: %s [it is %d bytes long]',
            data.toString().replace(/(\n)/gm,""),
            data.length);

    });

    // Let us know when the transmission is over
    socket.on('end', function() {

        console.log('EOT (End Of Transmission)');

    });

});

// Start listening on a specific port and address
server.listen(PORT, HOST, function() {

    console.log("I'm listening at %s, on port %s", HOST, PORT);

});

// When an error occurs, show it.
server.on('error', function(error) {

    console.error(error);

    // Close the connection after the error occurred.
    server.destroy();

});

TLS 套接字客户端

'use strict';

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

const PORT = 1337;
const HOST = '127.0.0.1'

// Pass the certs to the server and let it know to process even unauthorized certs.
var options = {
    key: fs.readFileSync('private-key.pem'),
    cert: fs.readFileSync('public-cert.pem'),
    rejectUnauthorized: false
};

var client = tls.connect(PORT, HOST, options, function() {

    // Check if the authorization worked
    if (client.authorized) {
        console.log("Connection authorized by a Certificate Authority.");
    } else {
        console.log("Connection not authorized: " + client.authorizationError)
    }

    // Send a friendly message
    client.write("I am the client sending you a message.");

});

client.on("data", function(data) {

    console.log('Received: %s [it is %d bytes long]',
        data.toString().replace(/(\n)/gm,""),
        data.length);

    // Close the connection after receiving the message
    client.end();

});

client.on('close', function() {

    console.log("Connection closed");

});

// When an error ocoures, show it.
client.on('error', function(error) {

    console.error(error);

    // Close the connection after the error occurred.
    client.destroy();

});