NodeJS和TLS,获取客户端证书

时间:2018-11-30 10:01:13

标签: node.js ssl tls1.2

我正在测试Node.JSTLS,并正在创建一个简单的服务器和客户端。 这似乎工作正常:

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');
});

我用server.js打印出客户端证书:

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

但是在Linux上进行cat client.crt时,我有以下长字符串:

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

server.js是否可以从客户端证书中获取该字符串?

1 个答案:

答案 0 :(得分:2)

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

这将以DER格式返回证书。您在client.crt中看到的是PEM格式的证书-基本上是二进制DER格式的base64,并添加了一些页眉和页脚行。您可以使用openssl x509 -in client.crt -outform der将PEM转换为DER。或者,您可以按照NodeJS: Validate certificate in DER format中的建议,在nodejs中将DER格式的证书转换为PEM。