old-keypairs.js/lib/x509-parser.js

77 lines
1.5 KiB
JavaScript
Raw Normal View History

2018-12-18 06:42:43 +00:00
'use strict';
var x509 = module.exports;
2018-12-18 07:34:40 +00:00
var PEM = require('./pem-parser.js');
var EC = require('./x509-ec-parser.js');
var RSA = require('./x509-rsa-parser.js');
2018-12-18 06:42:43 +00:00
2018-12-18 07:34:40 +00:00
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;
2018-12-18 06:42:43 +00:00
}
2018-12-18 07:34:40 +00:00
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);
2018-12-18 06:42:43 +00:00
}
2018-12-18 07:34:40 +00:00
// 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);
}
2018-12-18 06:42:43 +00:00
}
2018-12-18 07:34:40 +00:00
// 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
}
}
}
2018-12-18 06:42:43 +00:00
}
2018-12-18 07:34:40 +00:00
throw new Error("doesn't appear to be a valid key file. Tried PKCS1, SEC1, PKCS8, and SPKI/PKIX");
2018-12-18 06:42:43 +00:00
};