Browse Source

cleanup

master
AJ ONeal 5 years ago
parent
commit
c80e07ee7d
  1. 39
      lib/pem.js
  2. 8
      lib/rasha.js
  3. 2
      lib/x509.js

39
lib/pem.js

@ -3,43 +3,24 @@
var PEM = module.exports; var PEM = module.exports;
var Enc = require('./encoding.js'); var Enc = require('./encoding.js');
PEM.RSA_OBJID = '06 09 2A864886F70D010101'
.replace(/\s+/g, '').toLowerCase();
PEM.parseBlock = function pemToDer(pem) { PEM.parseBlock = function pemToDer(pem) {
var typ; var lines = pem.trim().split(/\n/);
var pub; var end = lines.length - 1;
var hex; var head = lines[0].match(/-----BEGIN (.*)-----/);
var der = Enc.base64ToBuf(pem.split(/\n/).filter(function (line, i) { var foot = lines[end].match(/-----END (.*)-----/);
if (0 === i) {
if (/ PUBLIC /.test(line)) {
pub = true;
} else if (/ PRIVATE /.test(line)) {
pub = false;
}
if (/ RSA /.test(line)) {
typ = 'RSA';
}
}
return !/---/.test(line);
}).join(''));
if (!typ) { if (head) {
hex = Enc.bufToHex(der); lines = lines.slice(1, end);
if (-1 !== hex.indexOf(PEM.RSA_OBJID)) { head = head[1];
typ = 'RSA'; if (head !== foot[1]) {
throw new Error("headers and footers do not match");
} }
} }
if (!typ) {
console.warn("Definitely not an RSA PKCS#8 because there's no RSA Object ID in the DER body.");
console.warn("Probably not an RSA PKCS#1 because 'RSA' wasn't in the PEM type string.");
}
return { kty: typ, pub: pub, der: der }; return { type: head, bytes: Enc.base64ToBuf(lines.join('')) };
}; };
PEM.packBlock = function (opts) { PEM.packBlock = function (opts) {
// TODO allow for headers?
return '-----BEGIN ' + opts.type + '-----\n' return '-----BEGIN ' + opts.type + '-----\n'
+ Enc.bufToBase64(opts.bytes).match(/.{1,64}/g).join('\n') + '\n' + Enc.bufToBase64(opts.bytes).match(/.{1,64}/g).join('\n') + '\n'
+ '-----END ' + opts.type + '-----' + '-----END ' + opts.type + '-----'

8
lib/rasha.js

@ -90,14 +90,14 @@ RSA.importSync = function (opts) {
var pem = opts.pem; var pem = opts.pem;
var block = PEM.parseBlock(pem); var block = PEM.parseBlock(pem);
//var hex = toHex(u8); //var hex = toHex(u8);
var asn1 = ASN1.parse(block.der); var asn1 = ASN1.parse(block.bytes);
var meta = x509.guess(block.der, asn1); var meta = x509.guess(block.bytes, asn1);
if ('pkcs1' === meta.format) { if ('pkcs1' === meta.format) {
jwk = x509.parsePkcs1(block.der, asn1, jwk); jwk = x509.parsePkcs1(block.bytes, asn1, jwk);
} else { } else {
jwk = x509.parsePkcs8(block.der, asn1, jwk); jwk = x509.parsePkcs8(block.bytes, asn1, jwk);
} }
if (opts.public) { if (opts.public) {

2
lib/x509.js

@ -1,7 +1,5 @@
'use strict'; 'use strict';
// TODO fun idea: create a template from an existing file
var x509 = module.exports; var x509 = module.exports;
var ASN1 = require('./asn1.js'); var ASN1 = require('./asn1.js');
var Enc = require('./encoding.js'); var Enc = require('./encoding.js');

Loading…
Cancel
Save