[英]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.