From d0157d32708720116592a7d59cf1431c1585723f Mon Sep 17 00:00:00 2001 From: AJ ONeal Date: Tue, 18 Dec 2018 00:46:07 -0700 Subject: [PATCH] shorten --- lib/x509-parser.js | 75 ++++++++++++++-------------------------------- 1 file changed, 22 insertions(+), 53 deletions(-) diff --git a/lib/x509-parser.js b/lib/x509-parser.js index 84691da..5672d5e 100644 --- a/lib/x509-parser.js +++ b/lib/x509-parser.js @@ -9,68 +9,37 @@ var RSA = require('./x509-rsa-parser.js'); x509.parse = function (opts) { var pem = opts.pem; var der = opts.der; - var typ; - var pub; - var prv; - var ec; - var rsa; if ('string' === opts.key) { pem = opts.key; } else if (opts.key && opts.key.length) { der = opts.key; } - if (pem) { - pem = PEM.parseBlock(pem); - der = pem.bytes; - typ = pem.type; - pub = /PUBLIC KEY/.test(typ); - prv = /PRIVATE KEY/.test(typ); - ec = /EC P/.test(typ); - rsa = /RSA P/.test(typ); - } + if (pem) { pem = PEM.parseBlock(pem); } + else { pem = { bytes: der, type: '' }; } + der = pem.bytes; + var typ = pem.type; + var pub = /PUBLIC KEY/.test(typ); + var prv = /PRIVATE KEY/.test(typ); + var ec = /EC P/.test(typ); + var rsa = /RSA P/.test(typ); // Try EC Private and Public keys - if (!rsa) { - if (!pub) { - try { - return EC.parsePkcs8(der); - } catch(e) { - try { - return EC.parseSec1(der); - } catch(e) { - // ignore - } - } - } - if (!prv) { - return EC.parseSpki(der); - } + if (!rsa && !pub) { + try { return EC.parsePkcs8(der); } catch(e) { /*ignore*/ } + try { return EC.parseSec1(der); } catch(e) { /*ignore*/ } + } else if (!rsa && !prv) { + try { return EC.parseSpki(der); } catch(e) { /*ignore*/ } } // Try RSA Private and Public keys - if (!ec) { - if (!pub) { - try { - return RSA.parsePkcs8(der); - } catch(e) { - try { - return RSA.parsePkcs1(der); - } catch(e) { - // ignore - } - } - } - if (!prv) { - try { - return RSA.parseSpki(der); - } catch(e) { - try { - return RSA.parsePublicPkcs1(der); - } catch(e) { - // ignore - } - } - } + if (!ec && !pub) { + try { return RSA.parsePkcs8(der); } catch(e) { /*ignore*/ } + try { return RSA.parsePkcs1(der); } catch(e) { /*ignore*/ } + } else if (!ec && !prv) { + try { return RSA.parseSpki(der); } catch(e) { /*ignore*/ } + try { return RSA.parsePublicPkcs1(der); } catch(e) { /*ignore*/ } } - throw new Error("doesn't appear to be a valid key file. Tried PKCS1, SEC1, PKCS8, and SPKI/PKIX"); + + throw new Error("Invalid or Unsupported key:\n" + + "Tried ASN.1 PEM/DER PKCS1, SEC1, PKCS8, and SPKI/PKIX (RSA and EC Private and Public)"); };