title: Node.js, simple TLS client/server
body: <p>I want create a simple secure client/server using TLS. I've follow instruction on the <a href="https://nodejs.org/api/tls.html" rel="nofollow">official doc</a>. But I don't know how to create self-signed certificate with openssl (does not work with me).</p>
  
  <p>Here code :</p>
  
  <p>server.js</p>
  
  <pre><code>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) =&gt; {
    console.log('server connected',
                socket.authorized ? 'authorized' : 'unauthorized');
    socket.write('welcome!\n');
    socket.setEncoding('utf8');
    socket.pipe(socket);
  });
  server.listen(8000, () =&gt; {
    console.log('server bound');
  });
  </code></pre>
  
  <p>client.js :</p>
  
  <pre><code>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, () =&gt; {
    console.log('client connected',
                socket.authorized ? 'authorized' : 'unauthorized');
    process.stdin.pipe(socket);
    process.stdin.resume();
  });
  socket.setEncoding('utf8');
  socket.on('data', (data) =&gt; {
    console.log(data);
  });
  socket.on('end', () =&gt; {
    server.close();
  });
  </code></pre>
  
  <p>I don't know why use two different key-pair :</p>
  
  <ul>
  <li>client-key.pem</li>
  <li>client-cert.pem</li>
  </ul>
  
  <p>and :</p>
  
  <ul>
  <li>server-key.pem</li>
  <li>server-cert.pem</li>
  </ul>
  
  <p>Anyone can exmplain me ? For work in self-signed.</p>
  
  <p>Sincerely,</p>
  
  <p>Yoratheon</p>