Compare commits

...

7 Commits

4 changed files with 135 additions and 32 deletions

View File

@ -51,6 +51,7 @@ return Keypairs.export({ jwk: pair.private, format: 'pkcs8' }).then(function (pe
``` ```
// PEM to JWK // PEM to JWK
return Keypairs.import({ pem: pem }).then(function (jwk) { return Keypairs.import({ pem: pem }).then(function (jwk) {
console.log(jwk);
}); });
``` ```
@ -164,9 +165,22 @@ Options
} }
``` ```
#### Keypairs.publish({ jwk: jwk }) #### Keypairs.publish({ jwk: jwk, exp: '3d', use: 'sig' })
**Synchronously** strips a key of its private parts and returns the public version. Promises a public key that adheres to the OIDC and Auth0 spec (plus expiry), suitable to be published to a JWKs URL:
```
{ "kty": "EC"
, "crv": "P-256"
, "x": "..."
, "y": "..."
, "kid": "..."
, "use": "sig"
, "exp": 1552074208
}
```
In particular this adds "use" and "exp".
#### Keypairs.thumbprint({ jwk: jwk }) #### Keypairs.thumbprint({ jwk: jwk })

View File

@ -10,10 +10,19 @@ var Keypairs = module.exports;
Keypairs.generate = function (opts) { Keypairs.generate = function (opts) {
opts = opts || {}; opts = opts || {};
var kty = opts.kty || opts.type; var kty = opts.kty || opts.type;
var p;
if ('RSA' === kty) { if ('RSA' === kty) {
return Rasha.generate(opts); p = Rasha.generate(opts);
} else {
p = Eckles.generate(opts);
} }
return Eckles.generate(opts); return p.then(function (pair) {
return Keypairs.thumbprint({ jwk: pair.public }).then(function (thumb) {
pair.private.kid = thumb; // maybe not the same id on the private key?
pair.public.kid = thumb;
return pair;
});
});
}; };
Keypairs.parse = function (opts) { Keypairs.parse = function (opts) {
@ -24,22 +33,26 @@ Keypairs.parse = function (opts) {
var pem; var pem;
var p; var p;
try { if (!opts.key || !opts.key.kty) {
jwk = JSON.parse(opts.key); try {
p = Keypairs.export({ jwk: jwk }).catch(function (e) { jwk = JSON.parse(opts.key);
pem = opts.key; p = Keypairs.export({ jwk: jwk }).catch(function (e) {
err = new Error("Not a valid jwk '" + JSON.stringify(jwk) + "':" + e.message); pem = opts.key;
err.code = "EINVALID"; err = new Error("Not a valid jwk '" + JSON.stringify(jwk) + "':" + e.message);
return Promise.reject(err); err.code = "EINVALID";
}).then(function () { return Promise.reject(err);
return jwk; }).then(function () {
}); return jwk;
} catch(e) { });
p = Keypairs.import({ pem: opts.key }).catch(function (e) { } catch(e) {
err = new Error("Could not parse key (type " + typeof opts.key + ") '" + opts.key + "': " + e.message); p = Keypairs.import({ pem: opts.key }).catch(function (e) {
err.code = "EPARSE"; err = new Error("Could not parse key (type " + typeof opts.key + ") '" + opts.key + "': " + e.message);
return Promise.reject(err); err.code = "EPARSE";
}); return Promise.reject(err);
});
}
} else {
p = Promise.resolve(opts.key);
} }
return p.then(function (jwk) { return p.then(function (jwk) {
@ -74,6 +87,11 @@ Keypairs.parseOrGenerate = function (opts) {
Keypairs.import = function (opts) { Keypairs.import = function (opts) {
return Eckles.import(opts).catch(function () { return Eckles.import(opts).catch(function () {
return Rasha.import(opts); return Rasha.import(opts);
}).then(function (jwk) {
return Keypairs.thumbprint({ jwk: jwk }).then(function (thumb) {
jwk.kid = thumb;
return jwk;
});
}); });
}; };
@ -93,6 +111,7 @@ Keypairs.neuter = Keypairs._neuter = function (opts) {
// trying to find the best balance of an immutable copy with custom attributes // trying to find the best balance of an immutable copy with custom attributes
var jwk = {}; var jwk = {};
Object.keys(opts.jwk).forEach(function (k) { Object.keys(opts.jwk).forEach(function (k) {
if ('undefined' === typeof opts.jwk[k]) { return; }
// ignore RSA and EC private parts // ignore RSA and EC private parts
if (-1 !== ['d', 'p', 'q', 'dp', 'dq', 'qi'].indexOf(k)) { return; } if (-1 !== ['d', 'p', 'q', 'dp', 'dq', 'qi'].indexOf(k)) { return; }
jwk[k] = JSON.parse(JSON.stringify(opts.jwk[k])); jwk[k] = JSON.parse(JSON.stringify(opts.jwk[k]));
@ -111,7 +130,7 @@ Keypairs.publish = function (opts) {
} else { } else {
if (opts.exp) { jwk.exp = setTime(opts.exp); } if (opts.exp) { jwk.exp = setTime(opts.exp); }
else if (opts.expiresIn) { jwk.exp = Math.round(Date.now()/1000) + opts.expiresIn; } else if (opts.expiresIn) { jwk.exp = Math.round(Date.now()/1000) + opts.expiresIn; }
else { jwk.exp = opts.expiresAt; } else if (opts.expiresAt) { jwk.exp = opts.expiresAt; }
} }
if (!jwk.use && false !== jwk.use) { jwk.use = "sig"; } if (!jwk.use && false !== jwk.use) { jwk.use = "sig"; }
@ -135,9 +154,9 @@ Keypairs.signJwt = function (opts) {
var header = opts.header || {}; var header = opts.header || {};
var claims = JSON.parse(JSON.stringify(opts.claims || {})); var claims = JSON.parse(JSON.stringify(opts.claims || {}));
header.typ = 'JWT'; header.typ = 'JWT';
if (!header.kid) {
header.kid = thumb; if (!header.kid) { header.kid = thumb; }
} if (!header.alg && opts.alg) { header.alg = opts.alg; }
if (!claims.iat && (false === claims.iat || false === opts.iat)) { if (!claims.iat && (false === claims.iat || false === opts.iat)) {
claims.iat = undefined; claims.iat = undefined;
} else if (!claims.iat) { } else if (!claims.iat) {
@ -178,7 +197,7 @@ Keypairs.signJws = function (opts) {
if (!opts.jwk) { if (!opts.jwk) {
throw new Error("opts.jwk must exist and must declare 'typ'"); throw new Error("opts.jwk must exist and must declare 'typ'");
} }
return ('RSA' === opts.jwk.typ) ? "RS256" : "ES256"; return ('RSA' === opts.jwk.kty) ? "RS256" : "ES256";
} }
function sign(pem) { function sign(pem) {
@ -210,13 +229,21 @@ Keypairs.signJws = function (opts) {
} }
// node specifies RSA-SHAxxx even whet it's actually ecdsa (it's all encoded x509 shasums anyway) // node specifies RSA-SHAxxx even whet it's actually ecdsa (it's all encoded x509 shasums anyway)
var nodeAlg = "RSA-SHA" + (((protect||header).alg||'').replace(/^[^\d]+/, '')||'256'); var nodeAlg = "SHA" + (((protect||header).alg||'').replace(/^[^\d]+/, '')||'256');
var protected64 = Enc.strToUrlBase64(protectedHeader); var protected64 = Enc.strToUrlBase64(protectedHeader);
var payload64 = Enc.bufToUrlBase64(payload); var payload64 = Enc.bufToUrlBase64(payload);
var sig = require('crypto') var binsig = require('crypto')
.createSign(nodeAlg) .createSign(nodeAlg)
.update(protect ? (protected64 + "." + payload64) : payload64) .update(protect ? (protected64 + "." + payload64) : payload64)
.sign(pem, 'base64') .sign(pem)
;
if ('EC' === opts.jwk.kty) {
// ECDSA JWT signatures differ from "normal" ECDSA signatures
// https://tools.ietf.org/html/rfc7518#section-3.4
binsig = ecdsaAsn1SigToJoseSig(binsig);
}
var sig = binsig.toString('base64')
.replace(/\+/g, '-') .replace(/\+/g, '-')
.replace(/\//g, '_') .replace(/\//g, '_')
.replace(/=/g, '') .replace(/=/g, '')
@ -230,6 +257,41 @@ Keypairs.signJws = function (opts) {
}; };
} }
function ecdsaAsn1SigToJoseSig(binsig) {
// should have asn1 sequence header of 0x30
if (0x30 !== binsig[0]) { throw new Error("Impossible EC SHA head marker"); }
var index = 2; // first ecdsa "R" header byte
var len = binsig[1];
var lenlen = 0;
// Seek length of length if length is greater than 127 (i.e. two 512-bit / 64-byte R and S values)
if (0x80 & len) {
lenlen = len - 0x80; // should be exactly 1
len = binsig[2]; // should be <= 130 (two 64-bit SHA-512s, plus padding)
index += lenlen;
}
// should be of BigInt type
if (0x02 !== binsig[index]) { throw new Error("Impossible EC SHA R marker"); }
index += 1;
var rlen = binsig[index];
var bits = 32;
if (rlen > 49) {
bits = 64;
} else if (rlen > 33) {
bits = 48;
}
var r = binsig.slice(index + 1, index + 1 + rlen).toString('hex');
var slen = binsig[index + 1 + rlen + 1]; // skip header and read length
var s = binsig.slice(index + 1 + rlen + 1 + 1).toString('hex');
if (2 *slen !== s.length) { throw new Error("Impossible EC SHA S length"); }
// There may be one byte of padding on either
while (r.length < 2*bits) { r = '00' + r; }
while (s.length < 2*bits) { s = '00' + s; }
if (2*(bits+1) === r.length) { r = r.slice(2); }
if (2*(bits+1) === s.length) { s = s.slice(2); }
return Buffer.concat([Buffer.from(r, 'hex'), Buffer.from(s, 'hex')]);
}
if (opts.pem && opts.jwk) { if (opts.pem && opts.jwk) {
return sign(opts.pem); return sign(opts.pem);
} else { } else {
@ -280,3 +342,25 @@ Enc.bufToUrlBase64 = function (buf) {
return Buffer.from(buf).toString('base64') return Buffer.from(buf).toString('base64')
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, ''); .replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
}; };
// For 'rsa-compat' module only
// PLEASE do not use these sync methods, they are deprecated
Keypairs._importSync = function (opts) {
try {
return Eckles.importSync(opts);
} catch(e) {
try {
return Rasha.importSync(opts);
} catch(e) {
console.error("options.pem does not appear to be a valid RSA or ECDSA public or private key");
}
}
};
// PLEASE do not use these, they are deprecated
Keypairs._exportSync = function (opts) {
if ('RSA' === opts.jwk.kty) {
return Rasha.exportSync(opts);
} else {
return Eckles.exportSync(opts);
}
};

View File

@ -1,7 +1,7 @@
{ {
"name": "keypairs", "name": "keypairs",
"version": "1.2.7", "version": "1.2.14",
"description": "Lightweight RSA/ECDSA keypair generation and JWK <-> PEM", "description": "Lightweight RSA/ECDSA keypair generation and JWK <-> PEM using node's native RSA and ECDSA support",
"main": "keypairs.js", "main": "keypairs.js",
"files": [ "files": [
"bin/keypairs.js" "bin/keypairs.js"
@ -21,7 +21,11 @@
"RSA", "RSA",
"ECDSA", "ECDSA",
"PEM", "PEM",
"JWK" "JWK",
"keypair",
"crypto",
"sign",
"verify"
], ],
"author": "AJ ONeal <coolaj86@gmail.com> (https://coolaj86.com/)", "author": "AJ ONeal <coolaj86@gmail.com> (https://coolaj86.com/)",
"license": "MPL-2.0", "license": "MPL-2.0",

View File

@ -1,6 +1,7 @@
var Keypairs = require('./'); var Keypairs = require('./');
/* global Promise*/ /* global Promise*/
console.info("This SHOULD result in an error message:");
Keypairs.parseOrGenerate({ key: '' }).then(function (pair) { Keypairs.parseOrGenerate({ key: '' }).then(function (pair) {
// should NOT have any warning output // should NOT have any warning output
if (!pair.private || !pair.public) { if (!pair.private || !pair.public) {
@ -90,7 +91,7 @@ Keypairs.parseOrGenerate({ key: '' }).then(function (pair) {
if ('NOERR' === e.code) { throw e; } if ('NOERR' === e.code) { throw e; }
return true; return true;
}) })
, Keypairs.signJwt({ jwk: pair.private, iss: 'https://example.com/', exp: '1h' }).then(function (jwt) { , Keypairs.signJwt({ jwk: pair.private, alg: 'ES512', iss: 'https://example.com/', exp: '1h' }).then(function (jwt) {
var parts = jwt.split('.'); var parts = jwt.split('.');
var now = Math.round(Date.now()/1000); var now = Math.round(Date.now()/1000);
var token = { var token = {