NodeJS: Validate certificate in DER format

好久不见. 提交于 2019-12-01 02:04:06

I think the PEM format is just the DER binary data that has been base64 encoded, split into 64 character lines, and wrapped between '-----BEGIN CERTIFICATE-----' and '-----END CERTIFICATE-----'.

So you could do this:

var prefix = '-----BEGIN CERTIFICATE-----\n';
var postfix = '-----END CERTIFICATE-----';
var pemText = prefix + derBuffer.toString('base64').match(/.{0,64}/g).join('\n') + postfix;

You will not need to put a '\n' before the postfix because the last match of the der buffer should be an empty string '', so there will be a '\n' at the end of derBuffer.toString('base64').match(/.{0,64}/g).join('\n')

Here's one way of doing it:

function derToPem(der) {
	var forge = require("node-forge");
	var derKey = forge.util.decode64(der);
	var asnObj = forge.asn1.fromDer(derKey);
	var asn1Cert = forge.pki.certificateFromAsn1(asnObj);
	return forge.pki.certificateToPem(asn1Cert);
};

Dominykas' answer was good, but in my case, I have a certificate that uses ECC and node-forge does not support it. So I've found a module called node-openssl-wrapper, which worked perfectly well because it encapsulates the openssl commands in a simple function call, like this:

co(function*() {
  var ossl = require('openssl-wrapper');
  var derCert = new Buffer('...'); // binary DER certificate
  var pemCert = yield ossl.qExec('x509', derCert, { inform: 'der', outform: 'pem' });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!