This commit is contained in:
AJ ONeal 2018-12-18 00:46:07 -07:00
parent 76b4528e19
commit d0157d3270
1 changed files with 22 additions and 53 deletions

View File

@ -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)");
};