Skip to content

Instantly share code, notes, and snippets.

@batazor
Forked from adisbladis/pkijs-decode-pem-node.js
Last active September 23, 2019 09:11
Show Gist options
  • Save batazor/58a48b551ab52c4e43a469e42d3bdceb to your computer and use it in GitHub Desktop.
Save batazor/58a48b551ab52c4e43a469e42d3bdceb to your computer and use it in GitHub Desktop.
Minimal example of loading a PEM certificate using pkijs (in nodejs)
#!/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 = pem.replace(/(-----(BEGIN|END) CERTIFICATE-----|[\n\r])/g, '')
// Now that we have decoded the cert it's now in DER-encoding
const der = Buffer.from(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))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment