Merge branch 'master' of ssh://git.coolaj86.com:22042/coolaj86/keypairs.js

This commit is contained in:
AJ ONeal 2018-12-17 21:00:16 -07:00
commit bf86aa8964
10 changed files with 1352 additions and 2 deletions

View File

@ -1,10 +1,14 @@
This is being ported from code from rsa-compat.js, greenlock.html (bacme.js), and others.
This is my project for the weekend. I expect to be finished today (Monday Nov 12th, 2018)
This was intended to be just a weekend project, but it's grown a bit.
* 2018-10-10 (Saturday) work has begun
* 2018-10-11 (Sunday) W00T! got a CSR generated for RSA with VanillaJS ArrayBuffer
* 2018-10-12 (Monday) Figuring out ECDSA CSRs right now
* 2018-10-15 (Thursday) ECDSA is a trixy hobbit... but I think I've got it...
* 2018-12-02 (Sunday) Been mostly done for a while, individually, slowly merging everything together
* [Rasha.js](https://git.coolaj86.com/coolaj86/rasha.js) (RSA utils)
* [Eckles.js](https://git.coolaj86.com/coolaj86/eckles.js) (EC utils)
<!--
Keypairs&trade; for node.js

235
lib/asn1.js Normal file
View File

@ -0,0 +1,235 @@
'use strict';
//
// A dumbed-down, minimal ASN.1 parser / packer combo
//
// Note: generally I like to write congruent code
// (i.e. output can be used as input and vice-versa)
// However, this seemed to be more readable and easier
// to use written as-is, asymmetrically.
// (I also generally prefer to export objects rather
// functions but, yet again, asthetics one in this case)
var Enc = require('./encoding.js');
//
// Packer
//
// Almost every ASN.1 type that's important for CSR
// can be represented generically with only a few rules.
var ASN1 = module.exports = function ASN1(/*type, hexstrings...*/) {
var args = Array.prototype.slice.call(arguments);
var typ = args.shift();
var str = args.join('').replace(/\s+/g, '').toLowerCase();
var len = (str.length/2);
var lenlen = 0;
var hex = typ;
// We can't have an odd number of hex chars
if (len !== Math.round(len)) {
throw new Error("invalid hex");
}
// The first byte of any ASN.1 sequence is the type (Sequence, Integer, etc)
// The second byte is either the size of the value, or the size of its size
// 1. If the second byte is < 0x80 (128) it is considered the size
// 2. If it is > 0x80 then it describes the number of bytes of the size
// ex: 0x82 means the next 2 bytes describe the size of the value
// 3. The special case of exactly 0x80 is "indefinite" length (to end-of-file)
if (len > 127) {
lenlen += 1;
while (len > 255) {
lenlen += 1;
len = len >> 8;
}
}
if (lenlen) { hex += Enc.numToHex(0x80 + lenlen); }
return hex + Enc.numToHex(str.length/2) + str;
};
// The Integer type has some special rules
ASN1.UInt = function UINT() {
var str = Array.prototype.slice.call(arguments).join('');
var first = parseInt(str.slice(0, 2), 16);
// If the first byte is 0x80 or greater, the number is considered negative
// Therefore we add a '00' prefix if the 0x80 bit is set
if (0x80 & first) { str = '00' + str; }
return ASN1('02', str);
};
// The Bit String type also has a special rule
ASN1.BitStr = function BITSTR() {
var str = Array.prototype.slice.call(arguments).join('');
// '00' is a mask of how many bits of the next byte to ignore
return ASN1('03', '00' + str);
};
//
// Parser
//
ASN1.ELOOP = "uASN1.js Error: iterated over 15+ elements (probably a malformed file)";
ASN1.EDEEP = "uASN1.js Error: element nested 20+ layers deep (probably a malformed file)";
// Container Types are Sequence 0x30, Octect String 0x04, Array? (0xA0, 0xA1)
// Value Types are Integer 0x02, Bit String 0x03, Null 0x05, Object ID 0x06,
// Sometimes Bit String is used as a container (RSA Pub Spki)
ASN1.VTYPES = [ 0x02, 0x03, 0x05, 0x06, 0x0c, 0x82 ];
ASN1.parse = function parseAsn1(buf, depth, ws) {
if (!ws) { ws = ''; }
if (depth >= 20) { throw new Error(ASN1.EDEEP); }
var index = 2; // we know, at minimum, data starts after type (0) and lengthSize (1)
var asn1 = { type: buf[0], lengthSize: 0, length: buf[1] };
var child;
var iters = 0;
var adjust = 0;
var adjustedLen;
// Determine how many bytes the length uses, and what it is
if (0x80 & asn1.length) {
asn1.lengthSize = 0x7f & asn1.length;
// I think that buf->hex->int solves the problem of Endianness... not sure
asn1.length = parseInt(Enc.bufToHex(buf.slice(index, index + asn1.lengthSize)), 16);
index += asn1.lengthSize;
}
// High-order bit Integers have a leading 0x00 to signify that they are positive.
// Bit Streams use the first byte to signify padding, which x.509 doesn't use.
if (0x00 === buf[index] && (0x02 === asn1.type || 0x03 === asn1.type)) {
// However, 0x00 on its own is a valid number
if (asn1.length > 1) {
index += 1;
adjust = -1;
}
}
adjustedLen = asn1.length + adjust;
//console.warn(ws + '0x' + Enc.numToHex(asn1.type), index, 'len:', asn1.length, asn1);
// this is a primitive value type
if (-1 !== ASN1.VTYPES.indexOf(asn1.type)) {
asn1.value = buf.slice(index, index + adjustedLen);
return asn1;
}
asn1.children = [];
//console.warn('1 len:', (2 + asn1.lengthSize + asn1.length), 'idx:', index, 'clen:', 0);
while (iters < 15 && index < (2 + asn1.length + asn1.lengthSize)) {
iters += 1;
child = ASN1.parse(buf.slice(index, index + adjustedLen), (depth || 0) + 1, ws + ' ');
// The numbers don't match up exactly and I don't remember why...
// probably something with adjustedLen or some such, but the tests pass
index += (2 + child.lengthSize + child.length);
//console.warn('2 len:', (2 + asn1.lengthSize + asn1.length), 'idx:', index, 'clen:', (2 + child.lengthSize + child.length));
if (index > (2 + asn1.lengthSize + asn1.length)) {
console.error(JSON.stringify(asn1, function (k, v) {
if ('value' === k) { return '0x' + Enc.bufToHex(v.data); } return v;
}, 2));
throw new Error("Parse error: child value length (" + child.length
+ ") is greater than remaining parent length (" + (asn1.length - index)
+ " = " + asn1.length + " - " + index + ")");
}
asn1.children.push(child);
//console.warn(ws + '0x' + Enc.numToHex(asn1.type), index, 'len:', asn1.length, asn1);
}
if (index !== (2 + asn1.lengthSize + asn1.length)) {
console.warn('index:', index, 'length:', (2 + asn1.lengthSize + asn1.length))
throw new Error("premature end-of-file");
}
if (iters >= 15) { throw new Error(ASN1.ELOOP); }
return asn1;
};
/*
ASN1._stringify = function(asn1) {
//console.log(JSON.stringify(asn1, null, 2));
//console.log(asn1);
var ws = '';
function write(asn1) {
console.log(ws, 'ch', Enc.numToHex(asn1.type), asn1.length);
if (!asn1.children) {
return;
}
asn1.children.forEach(function (a) {
ws += '\t';
write(a);
ws = ws.slice(1);
});
}
write(asn1);
};
*/
ASN1.tpl = function (asn1) {
//console.log(JSON.stringify(asn1, null, 2));
//console.log(asn1);
var sp = ' ';
var ws = sp;
var i = 0;
var vars = [];
var str = ws;
function write(asn1, k) {
str += "\n" + ws;
var val;
if ('number' !== typeof k) {
// ignore
} else {
str += ', ';
}
if (0x02 === asn1.type) {
str += "ASN1.UInt(";
} else if (0x03 === asn1.type) {
str += "ASN1.BitStr(";
} else {
str += "ASN1('" + Enc.numToHex(asn1.type) + "'";
}
if (!asn1.children) {
if (0x05 !== asn1.type) {
if (0x06 !== asn1.type) {
val = asn1.value || new Uint8Array(0);
vars.push("\n// 0x" + Enc.numToHex(val.byteLength) + " (" + val.byteLength + " bytes)\nopts.tpl" + i + " = '"
+ Enc.bufToHex(val) + "';");
if (0x02 !== asn1.type && 0x03 !== asn1.type) {
str += ", ";
}
str += "Enc.bufToHex(opts.tpl" + i + ")";
} else {
str += ", '" + Enc.bufToHex(asn1.value) + "'";
}
} else {
console.warn("XXXXXXXXXXXXXXXXXXXXX");
}
str += ")";
return ;
}
asn1.children.forEach(function (a, j) {
i += 1;
ws += sp;
write(a, j);
ws = ws.slice(sp.length);
});
str += "\n" + ws + ")";
}
write(asn1);
console.log('var opts = {};');
console.log(vars.join('\n') + '\n');
console.log();
console.log('function buildSchema(opts) {');
console.log(sp + 'return Enc.hexToBuf(' + str.slice(3) + ');');
console.log('}');
console.log();
console.log('buildSchema(opts);');
};
module.exports = ASN1;

493
lib/eckles.js Normal file
View File

@ -0,0 +1,493 @@
'use strict';
var EC = module.exports;
var Enc = require('./encoding.js');
var ASN1;
var PEM = require('./pem.js');
// 1.2.840.10045.3.1.7
// prime256v1 (ANSI X9.62 named elliptic curve)
var OBJ_ID_EC = '06 08 2A8648CE3D030107'.replace(/\s+/g, '').toLowerCase();
// 1.3.132.0.34
// secp384r1 (SECG (Certicom) named elliptic curve)
var OBJ_ID_EC_384 = '06 05 2B81040022'.replace(/\s+/g, '').toLowerCase();
// 1.2.840.10045.2.1
// ecPublicKey (ANSI X9.62 public key type)
var OBJ_ID_EC_PUB = '06 07 2A8648CE3D0201'.replace(/\s+/g, '').toLowerCase();
// 19 e c d s a - s h a 2 - n i s t p 2 5 6
var SSH_EC_P256 = '00000013 65 63 64 73 61 2d 73 68 61 32 2d 6e 69 73 74 70 32 35 36'
.replace(/\s+/g, '').toLowerCase();
// 19 e c d s a - s h a 2 - n i s t p 3 8 4
var SSH_EC_P384 = '00000013 65 63 64 73 61 2d 73 68 61 32 2d 6e 69 73 74 70 33 38 34'
.replace(/\s+/g, '').toLowerCase();
// The one good thing that came from the b***kchain hysteria: good EC documentation
// https://davidederosa.com/basic-blockchain-programming/elliptic-curve-keys/
EC.parseSec1 = function parseEcOnlyPrivkey(u8, jwk) {
var index = 7;
var len = 32;
var olen = OBJ_ID_EC.length/2;
if ("P-384" === jwk.crv) {
olen = OBJ_ID_EC_384.length/2;
index = 8;
len = 48;
}
if (len !== u8[index - 1]) {
throw new Error("Unexpected bitlength " + len);
}
// private part is d
var d = u8.slice(index, index + len);
// compression bit index
var ci = index + len + 2 + olen + 2 + 3;
var c = u8[ci];
var x, y;
if (0x04 === c) {
y = u8.slice(ci + 1 + len, ci + 1 + len + len);
} else if (0x02 !== c) {
throw new Error("not a supported EC private key");
}
x = u8.slice(ci + 1, ci + 1 + len);
return {
kty: jwk.kty
, crv: jwk.crv
, d: Enc.bufToUrlBase64(d)
//, dh: Enc.bufToHex(d)
, x: Enc.bufToUrlBase64(x)
//, xh: Enc.bufToHex(x)
, y: Enc.bufToUrlBase64(y)
//, yh: Enc.bufToHex(y)
};
};
EC.parsePkcs8 = function parseEcPkcs8(u8, jwk) {
var index = 24 + (OBJ_ID_EC.length/2);
var len = 32;
if ("P-384" === jwk.crv) {
index = 24 + (OBJ_ID_EC_384.length/2) + 2;
len = 48;
}
//console.log(index, u8.slice(index));
if (0x04 !== u8[index]) {
//console.log(jwk);
throw new Error("privkey not found");
}
var d = u8.slice(index+2, index+2+len);
var ci = index+2+len+5;
var xi = ci+1;
var x = u8.slice(xi, xi + len);
var yi = xi+len;
var y;
if (0x04 === u8[ci]) {
y = u8.slice(yi, yi + len);
} else if (0x02 !== u8[ci]) {
throw new Error("invalid compression bit (expected 0x04 or 0x02)");
}
return {
kty: jwk.kty
, crv: jwk.crv
, d: Enc.bufToUrlBase64(d)
//, dh: Enc.bufToHex(d)
, x: Enc.bufToUrlBase64(x)
//, xh: Enc.bufToHex(x)
, y: Enc.bufToUrlBase64(y)
//, yh: Enc.bufToHex(y)
};
};
EC.parseSpki = function parsePem(u8, jwk) {
var ci = 16 + OBJ_ID_EC.length/2;
var len = 32;
if ("P-384" === jwk.crv) {
ci = 16 + OBJ_ID_EC_384.length/2;
len = 48;
}
var c = u8[ci];
var xi = ci + 1;
var x = u8.slice(xi, xi + len);
var yi = xi + len;
var y;
if (0x04 === c) {
y = u8.slice(yi, yi + len);
} else if (0x02 !== c) {
throw new Error("not a supported EC private key");
}
return {
kty: jwk.kty
, crv: jwk.crv
, x: Enc.bufToUrlBase64(x)
//, xh: Enc.bufToHex(x)
, y: Enc.bufToUrlBase64(y)
//, yh: Enc.bufToHex(y)
};
};
EC.parsePkix = EC.parseSpki;
EC.parseSsh = function (pem) {
var jwk = { kty: 'EC', crv: null, x: null, y: null };
var b64 = pem.split(/\s+/g)[1];
var buf = Buffer.from(b64, 'base64');
var hex = Enc.bufToHex(buf);
var index = 40;
var len;
if (0 === hex.indexOf(SSH_EC_P256)) {
jwk.crv = 'P-256';
len = 32;
} else if (0 === hex.indexOf(SSH_EC_P384)) {
jwk.crv = 'P-384';
len = 48;
}
var x = buf.slice(index, index + len);
var y = buf.slice(index + len, index + len + len);
jwk.x = Enc.bufToUrlBase64(x);
jwk.y = Enc.bufToUrlBase64(y);
return jwk;
};
/*global Promise*/
EC.generate = function (opts) {
return Promise.resolve().then(function () {
var typ = 'ec';
var format = opts.format;
var encoding = opts.encoding;
var priv;
var pub = 'spki';
if (!format) {
format = 'jwk';
}
if (-1 !== [ 'spki', 'pkcs8', 'ssh' ].indexOf(format)) {
format = 'pkcs8';
}
if ('pem' === format) {
format = 'sec1';
encoding = 'pem';
} else if ('der' === format) {
format = 'sec1';
encoding = 'der';
}
if ('jwk' === format || 'json' === format) {
format = 'jwk';
encoding = 'json';
} else {
priv = format;
}
if (!encoding) {
encoding = 'pem';
}
if (priv) {
priv = { type: priv, format: encoding };
pub = { type: pub, format: encoding };
} else {
// jwk
priv = { type: 'sec1', format: 'pem' };
pub = { type: 'spki', format: 'pem' };
}
return new Promise(function (resolve, reject) {
return require('crypto').generateKeyPair(typ, {
namedCurve: opts.crv || opts.namedCurve || 'P-256'
, privateKeyEncoding: priv
, publicKeyEncoding: pub
}, function (err, pubkey, privkey) {
if (err) { reject(err); }
resolve({
private: privkey
, public: pubkey
});
});
}).then(function (keypair) {
if ('jwk' === format) {
return {
private: EC.importSync({ pem: keypair.private, format: priv.type })
, public: EC.importSync({ pem: keypair.public, format: pub.type, public: true })
};
}
if ('ssh' !== opts.format) {
return keypair;
}
return {
private: keypair.private
, public: EC.exportSync({ jwk: EC.importSync({
pem: keypair.public, format: format, public: true
}), format: opts.format, public: true })
};
});
});
};
EC.importSync = function importEcSync(opts) {
if (!opts || !opts.pem || 'string' !== typeof opts.pem) {
throw new Error("must pass { pem: pem } as a string");
}
if (0 === opts.pem.indexOf('ecdsa-sha2-')) {
return EC.parseSsh(opts.pem);
}
var pem = opts.pem;
var u8 = PEM.parseBlock(pem).bytes;
var hex = Enc.bufToHex(u8);
var jwk = { kty: 'EC', crv: null, x: null, y: null };
//console.log();
if (-1 !== hex.indexOf(OBJ_ID_EC)) {
jwk.crv = "P-256";
// PKCS8
if (0x02 === u8[3] && 0x30 === u8[6] && 0x06 === u8[8]) {
//console.log("PKCS8", u8[3].toString(16), u8[6].toString(16), u8[8].toString(16));
jwk = EC.parsePkcs8(u8, jwk);
// EC-only
} else if (0x02 === u8[2] && 0x04 === u8[5] && 0xA0 === u8[39]) {
//console.log("EC---", u8[2].toString(16), u8[5].toString(16), u8[39].toString(16));
jwk = EC.parseSec1(u8, jwk);
// SPKI/PKIK (Public)
} else if (0x30 === u8[2] && 0x06 === u8[4] && 0x06 === u8[13]) {
//console.log("SPKI-", u8[2].toString(16), u8[4].toString(16), u8[13].toString(16));
jwk = EC.parseSpki(u8, jwk);
// Error
} else {
//console.log("PKCS8", u8[3].toString(16), u8[6].toString(16), u8[8].toString(16));
//console.log("EC---", u8[2].toString(16), u8[5].toString(16), u8[39].toString(16));
//console.log("SPKI-", u8[2].toString(16), u8[4].toString(16), u8[13].toString(16));
throw new Error("unrecognized key format");
}
} else if (-1 !== hex.indexOf(OBJ_ID_EC_384)) {
jwk.crv = "P-384";
// PKCS8
if (0x02 === u8[3] && 0x30 === u8[6] && 0x06 === u8[8]) {
//console.log("PKCS8", u8[3].toString(16), u8[6].toString(16), u8[8].toString(16));
jwk = EC.parsePkcs8(u8, jwk);
// EC-only
} else if (0x02 === u8[3] && 0x04 === u8[6] && 0xA0 === u8[56]) {
//console.log("EC---", u8[3].toString(16), u8[6].toString(16), u8[56].toString(16));
jwk = EC.parseSec1(u8, jwk);
// SPKI/PKIK (Public)
} else if (0x30 === u8[2] && 0x06 === u8[4] && 0x06 === u8[13]) {
//console.log("SPKI-", u8[2].toString(16), u8[4].toString(16), u8[13].toString(16));
jwk = EC.parseSpki(u8, jwk);
// Error
} else {
//console.log("PKCS8", u8[3].toString(16), u8[6].toString(16), u8[8].toString(16));
//console.log("EC---", u8[3].toString(16), u8[6].toString(16), u8[56].toString(16));
//console.log("SPKI-", u8[2].toString(16), u8[4].toString(16), u8[13].toString(16));
throw new Error("unrecognized key format");
}
} else {
throw new Error("Supported key types are P-256 and P-384");
}
if (opts.public) {
if (true !== opts.public) {
throw new Error("options.public must be either `true` or `false` not ("
+ typeof opts.public + ") '" + opts.public + "'");
}
delete jwk.d;
}
return jwk;
};
EC.parse = function parseEc(opts) {
return Promise.resolve().then(function () {
return EC.importSync(opts);
});
};
EC.toJwk = EC.import = EC.parse;
EC.exportSync = function (opts) {
if (!opts || !opts.jwk || 'object' !== typeof opts.jwk) {
throw new Error("must pass { jwk: jwk } as a JSON object");
}
var jwk = JSON.parse(JSON.stringify(opts.jwk));
var format = opts.format;
if (opts.public || -1 !== [ 'spki', 'pkix', 'ssh', 'rfc4716' ].indexOf(format)) {
jwk.d = null;
}
if ('EC' !== jwk.kty) {
throw new Error("options.jwk.kty must be 'EC' for EC keys");
}
if (!jwk.d) {
if (!format || -1 !== [ 'spki', 'pkix' ].indexOf(format)) {
format = 'spki';
} else if (-1 !== [ 'ssh', 'rfc4716' ].indexOf(format)) {
format = 'ssh';
} else {
throw new Error("options.format must be 'spki' or 'ssh' for public EC keys, not ("
+ typeof format + ") " + format);
}
} else {
if (!format || 'sec1' === format) {
format = 'sec1';
} else if ('pkcs8' !== format) {
throw new Error("options.format must be 'sec1' or 'pkcs8' for private EC keys, not '" + format + "'");
}
}
if (-1 === [ 'P-256', 'P-384' ].indexOf(jwk.crv)) {
throw new Error("options.jwk.crv must be either P-256 or P-384 for EC keys, not '" + jwk.crv + "'");
}
if (!jwk.y) {
throw new Error("options.jwk.y must be a urlsafe base64-encoded either P-256 or P-384");
}
if ('sec1' === format) {
return PEM.packBlock({ type: "EC PRIVATE KEY", bytes: EC.packSec1(jwk) });
} else if ('pkcs8' === format) {
return PEM.packBlock({ type: "PRIVATE KEY", bytes: EC.packPkcs8(jwk) });
} else if (-1 !== [ 'spki', 'pkix' ].indexOf(format)) {
return PEM.packBlock({ type: "PUBLIC KEY", bytes: EC.packSpki(jwk) });
} else if (-1 !== [ 'ssh', 'rfc4716' ].indexOf(format)) {
return EC.packSsh(jwk);
} else {
throw new Error("Sanity Error: reached unreachable code block with format: " + format);
}
};
EC.pack = function (opts) {
return Promise.resolve().then(function () {
return EC.exportSync(opts);
});
};
EC.packSec1 = function (jwk) {
var d = Enc.base64ToHex(jwk.d);
var x = Enc.base64ToHex(jwk.x);
var y = Enc.base64ToHex(jwk.y);
var objId = ('P-256' === jwk.crv) ? OBJ_ID_EC : OBJ_ID_EC_384;
return Enc.hexToUint8(
ASN1('30'
, ASN1.UInt('01')
, ASN1('04', d)
, ASN1('A0', objId)
, ASN1('A1', ASN1.BitStr('04' + x + y)))
);
};
EC.packPkcs8 = function (jwk) {
var d = Enc.base64ToHex(jwk.d);
var x = Enc.base64ToHex(jwk.x);
var y = Enc.base64ToHex(jwk.y);
var objId = ('P-256' === jwk.crv) ? OBJ_ID_EC : OBJ_ID_EC_384;
return Enc.hexToUint8(
ASN1('30'
, ASN1.UInt('00')
, ASN1('30'
, OBJ_ID_EC_PUB
, objId
)
, ASN1('04'
, ASN1('30'
, ASN1.UInt('01')
, ASN1('04', d)
, ASN1('A1', ASN1.BitStr('04' + x + y)))))
);
};
EC.packSpki = function (jwk) {
var x = Enc.base64ToHex(jwk.x);
var y = Enc.base64ToHex(jwk.y);
var objId = ('P-256' === jwk.crv) ? OBJ_ID_EC : OBJ_ID_EC_384;
return Enc.hexToUint8(
ASN1('30'
, ASN1('30'
, OBJ_ID_EC_PUB
, objId
)
, ASN1.BitStr('04' + x + y))
);
};
EC.packPkix = EC.packSpki;
EC.packSsh = function (jwk) {
// Custom SSH format
var typ = 'ecdsa-sha2-nistp256';
var a = '32 35 36';
var b = '41';
var comment = jwk.crv + '@localhost';
if ('P-256' !== jwk.crv) {
typ = 'ecdsa-sha2-nistp384';
a = '33 38 34';
b = '61';
}
var x = Enc.base64ToHex(jwk.x);
var y = Enc.base64ToHex(jwk.y);
var ssh = Enc.hexToUint8(
('00 00 00 13 65 63 64 73 61 2d 73 68 61 32 2d 6e 69 73 74 70'
+ a + '00 00 00 08 6e 69 73 74 70' + a + '00 00 00' + b
+ '04' + x + y).replace(/\s+/g, '').toLowerCase()
);
return typ + ' ' + Enc.bufToBase64(ssh) + ' ' + comment;
};
//
// A dumbed-down, minimal ASN.1 packer
//
// Almost every ASN.1 type that's important for CSR
// can be represented generically with only a few rules.
ASN1 = function ASN1(/*type, hexstrings...*/) {
var args = Array.prototype.slice.call(arguments);
var typ = args.shift();
var str = args.join('').replace(/\s+/g, '').toLowerCase();
var len = (str.length/2);
var lenlen = 0;
var hex = typ;
// We can't have an odd number of hex chars
if (len !== Math.round(len)) {
throw new Error("invalid hex");
}
// The first byte of any ASN.1 sequence is the type (Sequence, Integer, etc)
// The second byte is either the size of the value, or the size of its size
// 1. If the second byte is < 0x80 (128) it is considered the size
// 2. If it is > 0x80 then it describes the number of bytes of the size
// ex: 0x82 means the next 2 bytes describe the size of the value
// 3. The special case of exactly 0x80 is "indefinite" length (to end-of-file)
if (len > 127) {
lenlen += 1;
while (len > 255) {
lenlen += 1;
len = len >> 8;
}
}
if (lenlen) { hex += Enc.numToHex(0x80 + lenlen); }
return hex + Enc.numToHex(str.length/2) + str;
};
// The Integer type has some special rules
ASN1.UInt = function UINT() {
var str = Array.prototype.slice.call(arguments).join('');
var first = parseInt(str.slice(0, 2), 16);
// If the first byte is 0x80 or greater, the number is considered negative
// Therefore we add a '00' prefix if the 0x80 bit is set
if (0x80 & first) { str = '00' + str; }
return ASN1('02', str);
};
// The Bit String type also has a special rule
ASN1.BitStr = function BITSTR() {
var str = Array.prototype.slice.call(arguments).join('');
// '00' is a mask of how many bits of the next byte to ignore
return ASN1('03', '00' + str);
};
EC.toPem = EC.export = EC.pack;

42
lib/encoding.js Normal file
View File

@ -0,0 +1,42 @@
'use strict';
var Enc = module.exports;
Enc.base64ToBuf = function (str) {
// node handles both base64 and urlBase64 equally
return Buffer.from(str, 'base64');
};
Enc.base64ToHex = function (b64) {
return Enc.bufToHex(Enc.base64ToBuf(b64));
};
Enc.bufToBase64 = function (u8) {
// Ensure a node buffer, even if TypedArray
return Buffer.from(u8).toString('base64');
};
Enc.bufToHex = function (u8) {
// Ensure a node buffer, even if TypedArray
return Buffer.from(u8).toString('hex');
};
Enc.bufToUrlBase64 = function (u8) {
return Enc.bufToBase64(u8)
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
};
Enc.hexToUint8 = function (hex) {
// TODO: I don't remember why I chose Uint8Array over Buffer...
var buf = Buffer.from(hex, 'hex');
var ab = buf.buffer.slice(buf.offset, buf.offset + buf.byteLength);
return new Uint8Array(ab);
};
Enc.numToHex = function (d) {
d = d.toString(16);
if (d.length % 2) {
return '0' + d;
}
return d;
};

28
lib/pem.js Normal file
View File

@ -0,0 +1,28 @@
'use strict';
var PEM = module.exports;
var Enc = require('./encoding.js');
PEM.parseBlock = function pemToDer(pem) {
var lines = pem.trim().split(/\n/);
var end = lines.length - 1;
var head = lines[0].match(/-----BEGIN (.*)-----/);
var foot = lines[end].match(/-----END (.*)-----/);
if (head) {
lines = lines.slice(1, end);
head = head[1];
if (head !== foot[1]) {
throw new Error("headers and footers do not match");
}
}
return { type: head, bytes: Enc.base64ToBuf(lines.join('')) };
};
PEM.packBlock = function (opts) {
return '-----BEGIN ' + opts.type + '-----\n'
+ Enc.bufToBase64(opts.bytes).match(/.{1,64}/g).join('\n') + '\n'
+ '-----END ' + opts.type + '-----'
;
};

204
lib/rasha.js Normal file
View File

@ -0,0 +1,204 @@
'use strict';
var RSA = module.exports;
var SSH = require('./ssh.js');
var PEM = require('./pem.js');
var x509 = require('./x509.js');
var ASN1 = require('./asn1.js');
/*global Promise*/
RSA.generate = function (opts) {
return Promise.resolve().then(function () {
var typ = 'rsa';
var format = opts.format;
var encoding = opts.encoding;
var priv;
var pub;
if (!format) {
format = 'jwk';
}
if ('spki' === format || 'pkcs8' === format) {
format = 'pkcs8';
pub = 'spki';
}
if ('pem' === format) {
format = 'pkcs1';
encoding = 'pem';
} else if ('der' === format) {
format = 'pkcs1';
encoding = 'der';
}
if ('jwk' === format || 'json' === format) {
format = 'jwk';
encoding = 'json';
} else {
priv = format;
pub = pub || format;
}
if (!encoding) {
encoding = 'pem';
}
if (priv) {
priv = { type: priv, format: encoding };
pub = { type: pub, format: encoding };
} else {
// jwk
priv = { type: 'pkcs1', format: 'pem' };
pub = { type: 'pkcs1', format: 'pem' };
}
return new Promise(function (resolve, reject) {
return require('crypto').generateKeyPair(typ, {
modulusLength: opts.modulusLength || 2048
, publicExponent: opts.publicExponent || 0x10001
, privateKeyEncoding: priv
, publicKeyEncoding: pub
}, function (err, pubkey, privkey) {
if (err) { reject(err); }
resolve({
private: privkey
, public: pubkey
});
});
}).then(function (keypair) {
if ('jwk' !== format) {
return keypair;
}
return {
private: RSA.importSync({ pem: keypair.private, format: priv.type })
, public: RSA.importSync({ pem: keypair.public, format: pub.type, public: true })
};
});
});
};
RSA.importSync = function (opts) {
if (!opts || !opts.pem || 'string' !== typeof opts.pem) {
throw new Error("must pass { pem: pem } as a string");
}
var jwk = { kty: 'RSA', n: null, e: null };
if (0 === opts.pem.indexOf('ssh-rsa ')) {
return SSH.parse(opts.pem, jwk);
}
var pem = opts.pem;
var block = PEM.parseBlock(pem);
//var hex = toHex(u8);
var asn1 = ASN1.parse(block.bytes);
var meta = x509.guess(block.bytes, asn1);
if ('pkcs1' === meta.format) {
jwk = x509.parsePkcs1(block.bytes, asn1, jwk);
} else {
jwk = x509.parsePkcs8(block.bytes, asn1, jwk);
}
if (opts.public) {
jwk = RSA.nueter(jwk);
}
return jwk;
};
RSA.parse = function parseRsa(opts) {
// wrapped in a promise for API compatibility
// with the forthcoming browser version
// (and potential future native node capability)
return Promise.resolve().then(function () {
return RSA.importSync(opts);
});
};
RSA.toJwk = RSA.import = RSA.parse;
/*
RSAPrivateKey ::= SEQUENCE {
version Version,
modulus INTEGER, -- n
publicExponent INTEGER, -- e
privateExponent INTEGER, -- d
prime1 INTEGER, -- p
prime2 INTEGER, -- q
exponent1 INTEGER, -- d mod (p-1)
exponent2 INTEGER, -- d mod (q-1)
coefficient INTEGER, -- (inverse of q) mod p
otherPrimeInfos OtherPrimeInfos OPTIONAL
}
*/
RSA.exportSync = function (opts) {
if (!opts || !opts.jwk || 'object' !== typeof opts.jwk) {
throw new Error("must pass { jwk: jwk }");
}
var jwk = JSON.parse(JSON.stringify(opts.jwk));
var format = opts.format;
var pub = opts.public;
if (pub || -1 !== [ 'spki', 'pkix', 'ssh', 'rfc4716' ].indexOf(format)) {
jwk = RSA.nueter(jwk);
}
if ('RSA' !== jwk.kty) {
throw new Error("options.jwk.kty must be 'RSA' for RSA keys");
}
if (!jwk.p) {
// TODO test for n and e
pub = true;
if (!format || 'pkcs1' === format) {
format = 'pkcs1';
} else if (-1 !== [ 'spki', 'pkix' ].indexOf(format)) {
format = 'spki';
} else if (-1 !== [ 'ssh', 'rfc4716' ].indexOf(format)) {
format = 'ssh';
} else {
throw new Error("options.format must be 'spki', 'pkcs1', or 'ssh' for public RSA keys, not ("
+ typeof format + ") " + format);
}
} else {
// TODO test for all necessary keys (d, p, q ...)
if (!format || 'pkcs1' === format) {
format = 'pkcs1';
} else if ('pkcs8' !== format) {
throw new Error("options.format must be 'pkcs1' or 'pkcs8' for private RSA keys");
}
}
if ('pkcs1' === format) {
if (jwk.d) {
return PEM.packBlock({ type: "RSA PRIVATE KEY", bytes: x509.packPkcs1(jwk) });
} else {
return PEM.packBlock({ type: "RSA PUBLIC KEY", bytes: x509.packPkcs1(jwk) });
}
} else if ('pkcs8' === format) {
return PEM.packBlock({ type: "PRIVATE KEY", bytes: x509.packPkcs8(jwk) });
} else if (-1 !== [ 'spki', 'pkix' ].indexOf(format)) {
return PEM.packBlock({ type: "PUBLIC KEY", bytes: x509.packSpki(jwk) });
} else if (-1 !== [ 'ssh', 'rfc4716' ].indexOf(format)) {
return SSH.pack({ jwk: jwk, comment: opts.comment });
} else {
throw new Error("Sanity Error: reached unreachable code block with format: " + format);
}
};
RSA.pack = function (opts) {
// wrapped in a promise for API compatibility
// with the forthcoming browser version
// (and potential future native node capability)
return Promise.resolve().then(function () {
return RSA.exportSync(opts);
});
};
RSA.toPem = RSA.export = RSA.pack;
// snip the _private_ parts... hAHAHAHA!
RSA.nueter = function (jwk) {
// (snip rather than new object to keep potential extra data)
// otherwise we could just do this:
// return { kty: jwk.kty, n: jwk.n, e: jwk.e };
[ 'p', 'q', 'd', 'dp', 'dq', 'qi' ].forEach(function (key) {
if (key in jwk) { jwk[key] = undefined; }
return jwk;
});
return jwk;
};

80
lib/ssh.js Normal file
View File

@ -0,0 +1,80 @@
'use strict';
var SSH = module.exports;
var Enc = require('./encoding.js');
// 7 s s h - r s a
SSH.RSA = '00000007 73 73 68 2d 72 73 61'.replace(/\s+/g, '').toLowerCase();
SSH.parse = function (pem, jwk) {
var parts = pem.split(/\s+/);
var buf = Enc.base64ToBuf(parts[1]);
var els = [];
var index = 0;
var len;
var i = 0;
var offset = (buf.byteOffset || 0);
// using dataview to be browser-compatible (I do want _some_ code reuse)
var dv = new DataView(buf.buffer.slice(offset, offset + buf.byteLength));
var el;
if (SSH.RSA !== Enc.bufToHex(buf.slice(0, SSH.RSA.length/2))) {
throw new Error("does not lead with ssh header");
}
while (index < buf.byteLength) {
i += 1;
if (i > 3) { throw new Error("15+ elements, probably not a public ssh key"); }
len = dv.getUint32(index, false);
index += 4;
el = buf.slice(index, index + len);
// remove BigUInt '00' prefix
if (0x00 === el[0]) {
el = el.slice(1);
}
els.push(el);
index += len;
}
jwk.n = Enc.bufToUrlBase64(els[2]);
jwk.e = Enc.bufToUrlBase64(els[1]);
return jwk;
};
SSH.pack = function (opts) {
var jwk = opts.jwk;
var header = 'ssh-rsa';
var comment = opts.comment || 'rsa@localhost';
var e = SSH._padHexInt(Enc.base64ToHex(jwk.e));
var n = SSH._padHexInt(Enc.base64ToHex(jwk.n));
var hex = [
SSH._numToUint32Hex(header.length)
, Enc.strToHex(header)
, SSH._numToUint32Hex(e.length/2)
, e
, SSH._numToUint32Hex(n.length/2)
, n
].join('');
return [ header, Enc.hexToBase64(hex), comment ].join(' ');
};
SSH._numToUint32Hex = function (num) {
var hex = num.toString(16);
while (hex.length < 8) {
hex = '0' + hex;
}
return hex;
};
SSH._padHexInt = function (hex) {
// BigInt is negative if the high order bit 0x80 is set,
// so ASN1, SSH, and many other formats pad with '0x00'
// to signifiy a positive number.
var i = parseInt(hex.slice(0, 2), 16);
if (0x80 & i) {
return '00' + hex;
}
return hex;
};

111
lib/telemetry.js Normal file
View File

@ -0,0 +1,111 @@
'use strict';
// We believe in a proactive approach to sustainable open source.
// As part of that we make it easy for you to opt-in to following our progress
// and we also stay up-to-date on telemetry such as operating system and node
// version so that we can focus our efforts where they'll have the greatest impact.
//
// Want to learn more about our Terms, Privacy Policy, and Mission?
// Check out https://therootcompany.com/legal/
var os = require('os');
var crypto = require('crypto');
var https = require('https');
var pkg = require('../package.json');
// to help focus our efforts in the right places
var data = {
package: pkg.name
, version: pkg.version
, node: process.version
, arch: process.arch || os.arch()
, platform: process.platform || os.platform()
, release: os.release()
};
function addCommunityMember(opts) {
setTimeout(function () {
var req = https.request({
hostname: 'api.therootcompany.com'
, port: 443
, path: '/api/therootcompany.com/public/community'
, method: 'POST'
, headers: { 'Content-Type': 'application/json' }
}, function (resp) {
// let the data flow, so we can ignore it
resp.on('data', function () {});
//resp.on('data', function (chunk) { console.log(chunk.toString()); });
resp.on('error', function () { /*ignore*/ });
//resp.on('error', function (err) { console.error(err); });
});
var obj = JSON.parse(JSON.stringify(data));
obj.action = 'updates';
try {
obj.ppid = ppid(obj.action);
} catch(e) {
// ignore
//console.error(e);
}
obj.name = opts.name || undefined;
obj.address = opts.email;
obj.community = 'node.js@therootcompany.com';
req.write(JSON.stringify(obj, 2, null));
req.end();
req.on('error', function () { /*ignore*/ });
//req.on('error', function (err) { console.error(err); });
}, 50);
}
function ping(action) {
setTimeout(function () {
var req = https.request({
hostname: 'api.therootcompany.com'
, port: 443
, path: '/api/therootcompany.com/public/ping'
, method: 'POST'
, headers: { 'Content-Type': 'application/json' }
}, function (resp) {
// let the data flow, so we can ignore it
resp.on('data', function () { });
//resp.on('data', function (chunk) { console.log(chunk.toString()); });
resp.on('error', function () { /*ignore*/ });
//resp.on('error', function (err) { console.error(err); });
});
var obj = JSON.parse(JSON.stringify(data));
obj.action = action;
try {
obj.ppid = ppid(obj.action);
} catch(e) {
// ignore
//console.error(e);
}
req.write(JSON.stringify(obj, 2, null));
req.end();
req.on('error', function (/*e*/) { /*console.error('req.error', e);*/ });
}, 50);
}
// to help identify unique installs without getting
// the personally identifiable info that we don't want
function ppid(action) {
var parts = [ action, data.package, data.version, data.node, data.arch, data.platform, data.release ];
var ifaces = os.networkInterfaces();
Object.keys(ifaces).forEach(function (ifname) {
if (/^en/.test(ifname) || /^eth/.test(ifname) || /^wl/.test(ifname)) {
if (ifaces[ifname] && ifaces[ifname].length) {
parts.push(ifaces[ifname][0].mac);
}
}
});
return crypto.createHash('sha1').update(parts.join(',')).digest('base64');
}
module.exports.ping = ping;
module.exports.joinCommunity = addCommunityMember;
if (require.main === module) {
ping('install');
//addCommunityMember({ name: "AJ ONeal", email: 'coolaj86@gmail.com' });
}

153
lib/x509.js Normal file
View File

@ -0,0 +1,153 @@
'use strict';
var x509 = module.exports;
var ASN1 = require('./asn1.js');
var Enc = require('./encoding.js');
x509.guess = function (der, asn1) {
// accepting der for compatability with other usages
var meta = { kty: 'RSA', format: 'pkcs1', public: true };
//meta.asn1 = ASN1.parse(u8);
if (asn1.children.every(function(el) {
return 0x02 === el.type;
})) {
if (2 === asn1.children.length) {
// rsa pkcs1 public
return meta;
} else if (asn1.children.length >= 9) {
// the standard allows for "otherPrimeInfos", hence at least 9
meta.public = false;
// rsa pkcs1 private
return meta;
} else {
throw new Error("not an RSA PKCS#1 public or private key (wrong number of ints)");
}
} else {
meta.format = 'pkcs8';
}
return meta;
};
x509.parsePkcs1 = function parseRsaPkcs1(buf, asn1, jwk) {
if (!asn1.children.every(function(el) {
return 0x02 === el.type;
})) {
throw new Error("not an RSA PKCS#1 public or private key (not all ints)");
}
if (2 === asn1.children.length) {
jwk.n = Enc.bufToUrlBase64(asn1.children[0].value);
jwk.e = Enc.bufToUrlBase64(asn1.children[1].value);
return jwk;
} else if (asn1.children.length >= 9) {
// the standard allows for "otherPrimeInfos", hence at least 9
jwk.n = Enc.bufToUrlBase64(asn1.children[1].value);
jwk.e = Enc.bufToUrlBase64(asn1.children[2].value);
jwk.d = Enc.bufToUrlBase64(asn1.children[3].value);
jwk.p = Enc.bufToUrlBase64(asn1.children[4].value);
jwk.q = Enc.bufToUrlBase64(asn1.children[5].value);
jwk.dp = Enc.bufToUrlBase64(asn1.children[6].value);
jwk.dq = Enc.bufToUrlBase64(asn1.children[7].value);
jwk.qi = Enc.bufToUrlBase64(asn1.children[8].value);
return jwk;
} else {
throw new Error("not an RSA PKCS#1 public or private key (wrong number of ints)");
}
};
x509.parsePkcs8 = function parseRsaPkcs8(buf, asn1, jwk) {
if (2 === asn1.children.length
&& 0x03 === asn1.children[1].type
&& 0x30 === asn1.children[1].value[0]) {
asn1 = ASN1.parse(asn1.children[1].value);
jwk.n = Enc.bufToUrlBase64(asn1.children[0].value);
jwk.e = Enc.bufToUrlBase64(asn1.children[1].value);
} else if (3 === asn1.children.length
&& 0x04 === asn1.children[2].type
&& 0x30 === asn1.children[2].children[0].type
&& 0x02 === asn1.children[2].children[0].children[0].type) {
asn1 = asn1.children[2].children[0];
jwk.n = Enc.bufToUrlBase64(asn1.children[1].value);
jwk.e = Enc.bufToUrlBase64(asn1.children[2].value);
jwk.d = Enc.bufToUrlBase64(asn1.children[3].value);
jwk.p = Enc.bufToUrlBase64(asn1.children[4].value);
jwk.q = Enc.bufToUrlBase64(asn1.children[5].value);
jwk.dp = Enc.bufToUrlBase64(asn1.children[6].value);
jwk.dq = Enc.bufToUrlBase64(asn1.children[7].value);
jwk.qi = Enc.bufToUrlBase64(asn1.children[8].value);
} else {
throw new Error("not an RSA PKCS#8 public or private key (wrong format)");
}
return jwk;
};
x509.packPkcs1 = function (jwk) {
var n = ASN1.UInt(Enc.base64ToHex(jwk.n));
var e = ASN1.UInt(Enc.base64ToHex(jwk.e));
if (!jwk.d) {
return Enc.hexToBuf(ASN1('30', n, e));
}
return Enc.hexToBuf(ASN1('30'
, ASN1.UInt('00')
, n
, e
, ASN1.UInt(Enc.base64ToHex(jwk.d))
, ASN1.UInt(Enc.base64ToHex(jwk.p))
, ASN1.UInt(Enc.base64ToHex(jwk.q))
, ASN1.UInt(Enc.base64ToHex(jwk.dp))
, ASN1.UInt(Enc.base64ToHex(jwk.dq))
, ASN1.UInt(Enc.base64ToHex(jwk.qi))
));
};
x509.packPkcs8 = function (jwk) {
if (!jwk.d) {
// Public RSA
return Enc.hexToBuf(ASN1('30'
, ASN1('30'
, ASN1('06', '2a864886f70d010101')
, ASN1('05')
)
, ASN1.BitStr(ASN1('30'
, ASN1.UInt(Enc.base64ToHex(jwk.n))
, ASN1.UInt(Enc.base64ToHex(jwk.e))
))
));
}
// Private RSA
return Enc.hexToBuf(ASN1('30'
, ASN1.UInt('00')
, ASN1('30'
, ASN1('06', '2a864886f70d010101')
, ASN1('05')
)
, ASN1('04'
, ASN1('30'
, ASN1.UInt('00')
, ASN1.UInt(Enc.base64ToHex(jwk.n))
, ASN1.UInt(Enc.base64ToHex(jwk.e))
, ASN1.UInt(Enc.base64ToHex(jwk.d))
, ASN1.UInt(Enc.base64ToHex(jwk.p))
, ASN1.UInt(Enc.base64ToHex(jwk.q))
, ASN1.UInt(Enc.base64ToHex(jwk.dp))
, ASN1.UInt(Enc.base64ToHex(jwk.dq))
, ASN1.UInt(Enc.base64ToHex(jwk.qi))
)
)
));
};
x509.packSpki = x509.packPkcs8;

View File

@ -1,6 +1,6 @@
{
"name": "keypairs",
"version": "0.0.3",
"version": "0.0.4",
"description": "Interchangeably use RSA & ECDSA with PEM and JWK for Signing, Verifying, CSR generation and JOSE. Ugh... that was a mouthful.",
"main": "index.js",
"scripts": {