Alfred Balle
Alfred Balle

Reputation: 1195

NodeJS and TLS, get client certificate

I'm testing Node.JS and TLS and are creating a simple server and client. This seems to work fine:

server.js:

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

const options = {
  key: fs.readFileSync('./server-certs/server.key'),
  cert: fs.readFileSync('./server-certs/server.crt'),
  rejectUnauthorized: false,
  requestCert: true
};

const server = tls.createServer(options, (socket) => {
  console.log('server connected',
              socket.authorized ? 'authorized' : 'unauthorized');

  console.log(socket.getPeerCertificate(true).raw);

  socket.write('welcome!\n');
  socket.setEncoding('utf8');
  socket.pipe(socket);
});
server.listen(8000, () => {
  console.log('server bound');
});

client.js:

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

const options = {
  key: fs.readFileSync('./client-certs/client.key'),
  cert: fs.readFileSync('./client-certs/client.crt')
};

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', () => {
  console.log('server ends connection');
});

With the server.js I print out the client cert:

console.log(socket.getPeerCertificate(true).raw);

But doing cat client.crt on Linux I have the following long string:

-----BEGIN CERTIFICATE-----
MIICsDCCAZgCCQC8miOEYnXCXDANBgkqhkiG9w0BAQsFADAaMQswCQYDVQQGEwJV
...
MHBcIlA2R3ssgfhlcSJcaR59LKA=
-----END CERTIFICATE-----

Is it possible for the server.js to get that string from the client certificate?

Upvotes: 4

Views: 6878

Answers (1)

Steffen Ullrich
Steffen Ullrich

Reputation: 123320

console.log(socket.getPeerCertificate(true).raw);

This returns the certificate in DER format. What you see in client.crt is the certificate in PEM format - which is basically base64 of the binary DER format with some header and footer line added. You could convert the PEM to DER using openssl x509 -in client.crt -outform der. Or you could convert the DER formatted certificate to PEM in nodejs as suggested in NodeJS: Validate certificate in DER format.

Upvotes: 3

Related Questions