77 lines
1.5 KiB
JavaScript
77 lines
1.5 KiB
JavaScript
'use strict';
|
|
|
|
var x509 = module.exports;
|
|
|
|
var PEM = require('./pem-parser.js');
|
|
var EC = require('./x509-ec-parser.js');
|
|
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);
|
|
}
|
|
|
|
// 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);
|
|
}
|
|
}
|
|
|
|
// 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
|
|
}
|
|
}
|
|
}
|
|
}
|
|
throw new Error("doesn't appear to be a valid key file. Tried PKCS1, SEC1, PKCS8, and SPKI/PKIX");
|
|
};
|