简体   繁体   English

如何在 Node.js Web 应用程序中访问原始(或完整)X509 证书

[英]How do I access the raw (or full) X509 Certificate in a Node.js web app

Given a simple Node.js app:给定一个简单的 Node.js 应用程序:

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

var options = {
  key: fs.readFileSync('mykey.pem'),
  cert: fs.readFileSync('mycert.pem')
};

https.createServer(options, function (req, res) {
  console.log(req.connection.getPeerCertificate());
  res.writeHead(200);
  res.end("hello world\n");
}).listen(8000);

Results in output to the console with a representation of the certificate, not the original (PEM) format.结果以证书的表示形式输出到控制台,而不是原始 (PEM) 格式。

Are there other methods available to access the original?还有其他方法可以访问原始文件吗?

The certificate object returned by getPeerCertificate has a raw field holding the DER encoding of the certificate. getPeerCertificate返回的证书对象有一个raw字段,其中包含证书的 DER 编码。

You can work with this DER encoding directly:您可以直接使用此 DER 编码:

  const cert_der = req.connection.getPeerCertificate().raw;
  console.log(cert_der);

In general, having the DER encoding should be sufficient.一般来说,使用 DER 编码就足够了。 However, if you need the PEM encoding, you can construct it by applying the base64 encoding to the DER encoding:但是,如果您需要 PEM 编码,则可以通过将 base64 编码应用于 DER 编码来构建它:

const os = require('os');

function der_to_pem(der) {
  const header = '-----BEGIN CERTIFICATE-----';
  const footer = '-----END CERTIFICATE-----';

  return [header, der.toString('base64'), footer].join(os.EOL);
}

You could then use this helper function to obtain the PEM encoding of the client certificate:然后,您可以使用此辅助函数来获取客户端证书的 PEM 编码:

  const cert_der = req.connection.getPeerCertificate().raw;
  console.log(der_to_pem(cert_der));

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

相关问题 在node.js中,如何从app.js中的另一个模块中的模块访问函数? - In node.js how do I access a function from app.js that is in a module that is in another module? 如何在我的node.js Web应用程序中包含jQuery代码? - How do I include jQuery code in my node.js web app? Meteor.js使用X509证书身份验证连接到Mongo - Meteor.js connection to Mongo using X509 certificate auth 如何将node.js Web应用程序上传到openshift? 它不是在git上,而是在我的计算机上? - How do I upload my node.js web app to openshift? It is NOT on git, but just on my computer? 如何仅在node.js heroku应用程序上授予对我的网站的访问权限 - How do i grant access to my site only on a node.js heroku app 使用 node js 将 PEM 字符串转换为 X509 证书而不使用 node-forge - Convert PEM string into X509 cert using node js without using node-forge 如何访问 node.js 解析器代码? - How do I access the node.js parser code? 如何使用带有X509证书的Javascript / JQuery进行REST请求? - How to use Javascript/JQuery make REST request with X509 certificate? 节点JS,如何从P12文件中提取X.509证书? - Node JS, how to extract X.509 Certificate from P12 file? 如何在Node.js应用程序的服务中插入传输器? - How do I insert a transporter into services in an Node.js app?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM