Created
May 10, 2018 03:04
-
-
Save adisbladis/c84e533e591b1737fedd26658021fef2 to your computer and use it in GitHub Desktop.
Minimal example of loading a PEM certificate using pkijs (in nodejs)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
// Minimal example of loading a PEM certificate using pkijs (in node) | |
// babel-polyfill needs to be loaded for pkijs | |
// It uses webcrypto which needs browser shims | |
require('babel-polyfill') | |
const Pkijs = require('pkijs') | |
const Asn1js = require('asn1js') | |
const FS = require('fs') | |
function decodeCert(pem) { | |
if(typeof pem !== 'string') { | |
throw new Error('Expected PEM as string') | |
} | |
// Load certificate in PEM encoding (base64 encoded DER) | |
const b64 = cert.replace(/(-----(BEGIN|END) CERTIFICATE-----|[\n\r])/g, '') | |
// Now that we have decoded the cert it's now in DER-encoding | |
const der = Buffer(b64, 'base64') | |
// And massage the cert into a BER encoded one | |
const ber = new Uint8Array(der).buffer | |
// And now Asn1js can decode things \o/ | |
const asn1 = Asn1js.fromBER(ber) | |
return new Pkijs.Certificate({ schema: asn1.result }) | |
} | |
const certFile = process.argv[2] | |
if(certFile === undefined) { | |
const file = require('path').basename(process.argv[1]) | |
console.error(`Usage: ${file} <pem_file>`) | |
process.exit(1) | |
} | |
const cert = FS.readFileSync(certFile).toString() | |
// Prints out cert as a map data structure | |
console.log(JSON.stringify(decodeCert(cert), null, 2)) |
DER is a subset of BER, so no conversion is needed. See here.
The code on line 25 (const ber = new Uint8Array(der).buffer
) is taking the backing ArrayBuffer
of the der
Buffer
. However, since a
Buffer
is a view of an ArrayBuffer
, and the backing ArrayBuffer
can be bigger (see here), this could potentially return bytes that were not part of the original Buffer
.
The safe way to do it would be to use ArrayBuffer.prototype.slice()
to extract a new ArrayBuffer
with just the relevant bytes:
const arrayBuffer = der.buffer.slice(der.byteOffset, der.byteOffset + der.length)
const asn1 = Asn1js.fromBER(arrayBuffer)
However, it seems that this is not needed. asn1js.fromBER()
also takes an ArrayBufferView
, which Buffer
fits. So we can just pass the
original DER Buffer directly:
const asn1 = Asn1js.fromBER(der)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Excellent!
A little glitch: line 19 -> pem