Skip to content

Commit

Permalink
tls: add derCertToPemCert()
Browse files Browse the repository at this point in the history
When calling getPeerCertificate(), the cert is
returned as a raw DER buffer. I often need to
convert these to PEM format. This was modeled after
Python's ssl.der_cert_to_pem_cert
  • Loading branch information
kaplanmaxe committed May 26, 2018
1 parent 39f2096 commit 3e8fffc
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
14 changes: 14 additions & 0 deletions lib/_tls_common.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
const { parseCertString } = require('internal/tls');
const { isArrayBufferView } = require('internal/util/types');
const tls = require('tls');
const { Buffer } = require('buffer');
const {
ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED,
ERR_INVALID_ARG_TYPE
Expand Down Expand Up @@ -249,3 +250,16 @@ exports.translatePeerCertificate = function translatePeerCertificate(c) {
}
return c;
};

exports.derCertToPemCert = function derCertToPemCert(cert) {
const chars = Buffer.from(cert).toString('base64').split('');
let formattedCert = '-----BEGIN CERTIFICATE-----';
for (var i = 0; i < chars.length; i++) {
if (i % 64 === 0) {
formattedCert += '\n';
}
formattedCert += chars[i];
}
formattedCert += '\n-----END CERTIFICATE-----\n';
return formattedCert;
};
1 change: 1 addition & 0 deletions lib/tls.js
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,7 @@ exports.parseCertString = internalUtil.deprecate(

exports.createSecureContext = _tls_common.createSecureContext;
exports.SecureContext = _tls_common.SecureContext;
exports.derCertToPemCert = _tls_common.derCertToPemCert;
exports.TLSSocket = _tls_wrap.TLSSocket;
exports.Server = _tls_wrap.Server;
exports.createServer = _tls_wrap.createServer;
Expand Down
26 changes: 26 additions & 0 deletions test/parallel/test-tls-der-cert-to-pem-cert.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
'use strict';
const common = require('../common');
const fixtures = require('../common/fixtures');
if (!common.hasCrypto) {
common.skip('missing crypto');
}
const tls = require('tls');

// Verify that detailed getPeerCertificate() return value has all certs.

const {
assert, connect, keys
} = require(fixtures.path('tls-connect'));

connect({
client: { rejectUnauthorized: false },
server: keys.agent1,
}, function(err, pair, cleanup) {
assert.ifError(err);
const socket = pair.client.conn;
const peerCert = socket.getPeerCertificate();
const pemCert = tls.derCertToPemCert(peerCert.raw);
assert.strictEqual(pemCert, keys.agent1.cert);

return cleanup();
});

0 comments on commit 3e8fffc

Please sign in to comment.