简体   繁体   English

Node.js,简单的 TLS 客户端/服务器

[英]Node.js, simple TLS client/server

I want create a simple secure client/server using TLS.我想使用 TLS 创建一个简单的安全客户端/服务器。 I've follow instruction on the official doc .我已经按照官方文档的说明进行操作。 But I don't know how to create self-signed certificate with openssl (does not work with me).但我不知道如何使用 openssl 创建自签名证书(不适用于我)。

Here code :这里的代码:

server.js服务器.js

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

const options = {
  key: fs.readFileSync('server-key.pem'),
  cert: fs.readFileSync('server-cert.pem'),

  // This is necessary only if using the client certificate authentication.
  requestCert: true,

  // This is necessary only if the client uses the self-signed certificate.
  ca: [ fs.readFileSync('client-cert.pem') ]
};

const server = tls.createServer(options, (socket) => {
  console.log('server connected',
              socket.authorized ? 'authorized' : 'unauthorized');
  socket.write('welcome!\n');
  socket.setEncoding('utf8');
  socket.pipe(socket);
});
server.listen(8000, () => {
  console.log('server bound');
});

client.js :客户端.js:

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

const options = {
  // Necessary only if using the client certificate authentication
  key: fs.readFileSync('client-key.pem'),
  cert: fs.readFileSync('client-cert.pem'),

  // Necessary only if the server uses the self-signed certificate
  ca: [ fs.readFileSync('server-cert.pem') ]
};

const socket = tls.connect(8000, options, () => {
  console.log('client connected',
              socket.authorized ? 'authorized' : 'unauthorized');
  process.stdin.pipe(socket);
  process.stdin.resume();
});
socket.setEncoding('utf8');
socket.on('data', (data) => {
  console.log(data);
});
socket.on('end', () => {
  server.close();
});

I don't know why use two different key-pair :我不知道为什么要使用两个不同的密钥对:

  • client-key.pem客户端密钥.pem
  • client-cert.pem客户端证书.pem

and :和:

  • server-key.pem服务器密钥.pem
  • server-cert.pem服务器-cert.pem

Anyone can exmplain me ?任何人都可以解释我吗? For work in self-signed.对于自签名的工作。

Sincerely,真诚的,

Yoratheon约拉神

I solve my problem.我解决了我的问题。

Solution here解决方案在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM