commit 10f815a9227019d791e225fb349b58d66c416c03 Author: AJ ONeal Date: Sun Nov 18 22:50:08 2018 -0700 v0.1.0: Full PEM-to-JWK support diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f26f699 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +x +.*.sw* diff --git a/README.md b/README.md new file mode 100644 index 0000000..ab912b3 --- /dev/null +++ b/README.md @@ -0,0 +1,42 @@ +eckles.js +========= + +ECDSA tools. Lightweight. Zero Dependencies. Universal compatibility. + +> I _just_ cleaned up the PEM-to-JWK functionality enough to publish. +> I also have the JWK-to-PEM functionality _mostly_ built, but not enough to publish. + +* P-256 (prime256v1, secp256r1) +* P-384 (secp384r1) +* PKCS#8 +* SEC1/X9.62 +* PEM-to-JWK + +```js +eckles.import({ pem: pem }).then(function (jwk) { + console.log(jwk); +}); +``` + + + +Goals +----- + +* Focused support for P-256 and P-384, which are already universally supported. +* Convert both ways +* Browser support as well diff --git a/bin/eckles.js b/bin/eckles.js new file mode 100755 index 0000000..f3f7581 --- /dev/null +++ b/bin/eckles.js @@ -0,0 +1,14 @@ +#!/usr/bin/env node +'use strict'; + +var fs = require('fs'); +var eckles = require('../index.js'); + +var infile = process.argv[2]; +//var outfile = process.argv[3]; + +var keypem = fs.readFileSync(infile, 'ascii'); + +eckles.import({ pem: keypem }).then(function (jwk) { + console.log(jwk); +}); diff --git a/fixtures/privkey-ec-p256.pkcs8.pem b/fixtures/privkey-ec-p256.pkcs8.pem new file mode 100644 index 0000000..6f96050 --- /dev/null +++ b/fixtures/privkey-ec-p256.pkcs8.pem @@ -0,0 +1,5 @@ +-----BEGIN EC PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgiYydo27aNGO9DBUW +eGEPD8oNi1LZDqfxPmQlieLBjVShRANCAAQhPVJYvGxpw+ITlnXqOSikCfz/7zms +yODIKiSueMN+3pj9icDgDnTJl7sKcWyp4Nymc9u5s/pyliJVyd680hjK +-----END EC PRIVATE KEY----- diff --git a/fixtures/privkey-ec-p256.sec1.pem b/fixtures/privkey-ec-p256.sec1.pem new file mode 100644 index 0000000..6dca08a --- /dev/null +++ b/fixtures/privkey-ec-p256.sec1.pem @@ -0,0 +1,5 @@ +-----BEGIN EC PRIVATE KEY----- +MHcCAQEEIImMnaNu2jRjvQwVFnhhDw/KDYtS2Q6n8T5kJYniwY1UoAoGCCqGSM49 +AwEHoUQDQgAEIT1SWLxsacPiE5Z16jkopAn8/+85rMjgyCokrnjDft6Y/YnA4A50 +yZe7CnFsqeDcpnPbubP6cpYiVcnevNIYyg== +-----END EC PRIVATE KEY----- diff --git a/fixtures/privkey-ec-p384.pkcs8.pem b/fixtures/privkey-ec-p384.pkcs8.pem new file mode 100644 index 0000000..db0261b --- /dev/null +++ b/fixtures/privkey-ec-p384.pkcs8.pem @@ -0,0 +1,6 @@ +-----BEGIN EC PRIVATE KEY----- +MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDBeXK4IRZJNNLxTv078 +zPTnPXy+HiRvXSzO+7/ul1e4ZZXqV8TI8THJRhawDoDaR1WhZANiAATbMRTRsoJr +t6Mosgnyg8acuGqHHKK/j/DfwrZrRI8Lp2xJ33+CU0nyVyq/Sx9/kZtUPiOe7zdL +qxyfr9N4CPcRk5EQZs6zp3OhWlq6Cf5dAwzIL07hUtsMMUYFlMmUyxs= +-----END EC PRIVATE KEY----- diff --git a/fixtures/privkey-ec-p384.sec1.pem b/fixtures/privkey-ec-p384.sec1.pem new file mode 100644 index 0000000..d6b6b62 --- /dev/null +++ b/fixtures/privkey-ec-p384.sec1.pem @@ -0,0 +1,6 @@ +-----BEGIN EC PRIVATE KEY----- +MIGkAgEBBDBeXK4IRZJNNLxTv078zPTnPXy+HiRvXSzO+7/ul1e4ZZXqV8TI8THJ +RhawDoDaR1WgBwYFK4EEACKhZANiAATbMRTRsoJrt6Mosgnyg8acuGqHHKK/j/Df +wrZrRI8Lp2xJ33+CU0nyVyq/Sx9/kZtUPiOe7zdLqxyfr9N4CPcRk5EQZs6zp3Oh +Wlq6Cf5dAwzIL07hUtsMMUYFlMmUyxs= +-----END EC PRIVATE KEY----- diff --git a/fixtures/pub-ec-p256.spki.pem b/fixtures/pub-ec-p256.spki.pem new file mode 100644 index 0000000..abb69b3 --- /dev/null +++ b/fixtures/pub-ec-p256.spki.pem @@ -0,0 +1,4 @@ +-----BEGIN PUBLIC KEY----- +MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEIT1SWLxsacPiE5Z16jkopAn8/+85 +rMjgyCokrnjDft6Y/YnA4A50yZe7CnFsqeDcpnPbubP6cpYiVcnevNIYyg== +-----END PUBLIC KEY----- diff --git a/fixtures/pub-ec-p384.spki.pem b/fixtures/pub-ec-p384.spki.pem new file mode 100644 index 0000000..31a503a --- /dev/null +++ b/fixtures/pub-ec-p384.spki.pem @@ -0,0 +1,5 @@ +-----BEGIN PUBLIC KEY----- +MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE2zEU0bKCa7ejKLIJ8oPGnLhqhxyiv4/w +38K2a0SPC6dsSd9/glNJ8lcqv0sff5GbVD4jnu83S6scn6/TeAj3EZOREGbOs6dz +oVpaugn+XQMMyC9O4VLbDDFGBZTJlMsb +-----END PUBLIC KEY----- diff --git a/index.js b/index.js new file mode 100644 index 0000000..2d5fa4d --- /dev/null +++ b/index.js @@ -0,0 +1,2 @@ +'use strict'; +module.exports = require('./lib/eckles.js'); diff --git a/lib/eckles.js b/lib/eckles.js new file mode 100644 index 0000000..85eced8 --- /dev/null +++ b/lib/eckles.js @@ -0,0 +1,243 @@ +'use strict'; + +var Hex = {}; + +// 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(); + + +// The one good thing that came from the b***kchain hysteria: good EC documentation +// https://davidederosa.com/basic-blockchain-programming/elliptic-curve-keys/ + +var PEM = {}; +PEM._toUrlSafeBase64 = function (u8) { + //console.log('Len:', u8.byteLength); + return Buffer.from(u8).toString('base64') + .replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, ''); +}; + +function toHex(ab) { + var hex = []; + var u8 = new Uint8Array(ab); + var size = u8.byteLength; + var i; + var h; + for (i = 0; i < size; i += 1) { + h = u8[i].toString(16); + if (2 === h.length) { + hex.push(h); + } else { + hex.push('0' + h); + } + } + return hex.join('').replace(/\s+/g, '').toLowerCase(); +} +Hex.fromAB = toHex; + +function parsePem(pem) { + var typ; + var pub; + var crv; + var der = Buffer.from(pem.split(/\n/).filter(function (line, i) { + if (0 === i) { + if (/ PUBLIC /.test(line)) { + pub = true; + } else if (/ PRIVATE /.test(line)) { + pub = false; + } + if (/ EC/.test(line)) { + typ = 'EC'; + } + } + return !/---/.test(line); + }).join(''), 'base64'); + + if (!typ || 'EC' === typ) { + var hex = toHex(der); + if (-1 !== hex.indexOf(OBJ_ID_EC)) { + typ = 'EC'; + crv = 'P-256'; + } else if (-1 !== hex.indexOf(OBJ_ID_EC_384)) { + typ = 'EC'; + crv = 'P-384'; + } else { + // TODO support P-384 as well (but probably nothing else) + console.warn("unsupported ec curve"); + } + } + + return { typ: typ, pub: pub, der: der, crv: crv }; +} + +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: PEM._toUrlSafeBase64(d) + //, dh: d + , x: PEM._toUrlSafeBase64(x) + //, xh: x + , y: PEM._toUrlSafeBase64(y) + //, yh: y + }; +} +function parseEcPkcs8Privkey(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: PEM._toUrlSafeBase64(d) + //, dh: d + , x: PEM._toUrlSafeBase64(x) + //, xh: x + , y: PEM._toUrlSafeBase64(y) + //, yh: y + }; +} +function parseEcPub(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: PEM._toUrlSafeBase64(x) + //, xh: x + , y: PEM._toUrlSafeBase64(y) + //, yh: y + }; +} + +/*global Promise*/ +function parseEcPrivkey(opts) { + return Promise.resolve().then(function () { + if (!opts || !opts.pem) { + throw new Error("must pass { pem: pem }"); + } + var pem = opts.pem; + var u8 = parsePem(pem).der; + var hex = toHex(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)); + return parseEcPkcs8Privkey(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)); + return parseEcOnlyPrivkey(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)); + return parseEcPub(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)); + return parseEcPkcs8Privkey(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)); + return parseEcOnlyPrivkey(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)); + return parseEcPub(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"); + } + }); +} + +module.exports.import = parseEcPrivkey; diff --git a/lib/telemetry.js b/lib/telemetry.js new file mode 100644 index 0000000..c628a2d --- /dev/null +++ b/lib/telemetry.js @@ -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' }); +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..93ee963 --- /dev/null +++ b/package.json @@ -0,0 +1,34 @@ +{ + "name": "eckles", + "version": "0.1.0", + "description": "A focused, zero-dependency library for perfect universal ECDSA P-256 (prime256v1, secp256r1) and P-384 (secp384r1) support.", + "main": "index.js", + "bin": { + "eckles": "bin/eckles.js" + }, + "directories": { + "lib": "lib" + }, + "scripts": { + "postinstall": "node lib/telemetry.js event:install", + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "https://git.coolaj86.com/coolaj86/eckles.js" + }, + "keywords": [ + "zero-dependency", + "ec", + "ecdsa", + "jwk", + "pem", + "p-256", + "p-384", + "prime256v1", + "secp256r1", + "secp384r1" + ], + "author": "AJ ONeal (https://coolaj86.com/)", + "license": "MPL-2.0" +} diff --git a/test.sh b/test.sh new file mode 100644 index 0000000..2706656 --- /dev/null +++ b/test.sh @@ -0,0 +1,15 @@ +#/bin/bash + +echo "" +echo "" +node bin/eckles.js fixtures/privkey-ec-p256.sec1.pem +node bin/eckles.js fixtures/privkey-ec-p256.pkcs8.pem +node bin/eckles.js fixtures/pub-ec-p256.spki.pem + +echo "" +echo "" +node bin/eckles.js fixtures/privkey-ec-p384.sec1.pem +node bin/eckles.js fixtures/privkey-ec-p384.pkcs8.pem +node bin/eckles.js fixtures/pub-ec-p384.spki.pem + +echo ""