Skip to content

Instantly share code, notes, and snippets.

@adisbladis
Created May 10, 2018 03:04
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save adisbladis/c84e533e591b1737fedd26658021fef2 to your computer and use it in GitHub Desktop.
Save adisbladis/c84e533e591b1737fedd26658021fef2 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 = 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))
@PriitParmakson
Copy link

PriitParmakson commented Dec 18, 2018

Excellent!

A little glitch: line 19 -> pem

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment