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 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)) |
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