Compare commits
9 Commits
Author | SHA1 | Date | |
---|---|---|---|
b22f957124 | |||
48bee9204d | |||
5dc3795a17 | |||
3c84a7e1bd | |||
65db78a3c5 | |||
e04557c84a | |||
083cc6d73e | |||
885a00c3ae | |||
34d0ca9f13 |
71
README.md
71
README.md
@ -29,26 +29,50 @@ and [Rasha.js (RSA)](https://git.coolaj86.com/coolaj86/rasha.js/).
|
|||||||
|
|
||||||
# Usage
|
# Usage
|
||||||
|
|
||||||
A brief (albeit somewhat nonsensical) introduction to the APIs:
|
A brief introduction to the APIs:
|
||||||
|
|
||||||
```
|
```
|
||||||
|
// generate a new keypair as jwk
|
||||||
|
// (defaults to EC P-256 when no options are specified)
|
||||||
Keypairs.generate().then(function (pair) {
|
Keypairs.generate().then(function (pair) {
|
||||||
return Keypairs.export({ jwk: pair.private }).then(function (pem) {
|
console.log(pair.private);
|
||||||
|
console.log(pair.public);
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
```
|
||||||
|
// JWK to PEM
|
||||||
|
// (supports various 'format' and 'encoding' options)
|
||||||
|
return Keypairs.export({ jwk: pair.private, format: 'pkcs8' }).then(function (pem) {
|
||||||
|
console.log(pem);
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
```
|
||||||
|
// PEM to JWK
|
||||||
return Keypairs.import({ pem: pem }).then(function (jwk) {
|
return Keypairs.import({ pem: pem }).then(function (jwk) {
|
||||||
|
console.log(jwk);
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
```
|
||||||
|
// Thumbprint a JWK (SHA256)
|
||||||
return Keypairs.thumbprint({ jwk: jwk }).then(function (thumb) {
|
return Keypairs.thumbprint({ jwk: jwk }).then(function (thumb) {
|
||||||
console.log(thumb);
|
console.log(thumb);
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
```
|
||||||
|
// Sign a JWT (aka compact JWS)
|
||||||
return Keypairs.signJwt({
|
return Keypairs.signJwt({
|
||||||
jwk: keypair.private
|
jwk: pair.private
|
||||||
|
, iss: 'https://example.com'
|
||||||
|
, exp: '1h'
|
||||||
|
// optional claims
|
||||||
, claims: {
|
, claims: {
|
||||||
iss: 'https://example.com'
|
|
||||||
, sub: 'jon.doe@gmail.com'
|
, sub: 'jon.doe@gmail.com'
|
||||||
, exp: Math.round(Date.now()/1000) + (3 * 24 * 60 * 60)
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
```
|
```
|
||||||
|
|
||||||
By default ECDSA keys will be used since they've had native support in node
|
By default ECDSA keys will be used since they've had native support in node
|
||||||
@ -56,9 +80,9 @@ _much_ longer than RSA has, and they're smaller, and faster to generate.
|
|||||||
|
|
||||||
## API Overview
|
## API Overview
|
||||||
|
|
||||||
* generate
|
* generate (JWK)
|
||||||
* parse
|
* parse (PEM)
|
||||||
* parseOrGenerate
|
* parseOrGenerate (PEM to JWK)
|
||||||
* import (PEM-to-JWK)
|
* import (PEM-to-JWK)
|
||||||
* export (JWK-to-PEM, private or public)
|
* export (JWK-to-PEM, private or public)
|
||||||
* publish (Private JWK to Public JWK)
|
* publish (Private JWK to Public JWK)
|
||||||
@ -141,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 })
|
||||||
|
|
||||||
@ -155,11 +192,17 @@ Returns a JWT (otherwise known as a protected JWS in "compressed" format).
|
|||||||
|
|
||||||
```js
|
```js
|
||||||
{ jwk: jwk
|
{ jwk: jwk
|
||||||
|
// required claims
|
||||||
|
, iss: 'https://example.com'
|
||||||
|
, exp: '15m'
|
||||||
|
// all optional claims
|
||||||
, claims: {
|
, claims: {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Exp may be human readable duration (i.e. 1h, 15m, 30s) or a datetime in seconds.
|
||||||
|
|
||||||
Header defaults:
|
Header defaults:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
609
bin/keypairs.js
609
bin/keypairs.js
@ -1,611 +1,12 @@
|
|||||||
#!/usr/bin/env node
|
#!/usr/bin/env node
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
// I'm not proud of the way this code is written - it snowballed from a thought
|
var cmd = "npm install --global keypairs-cli";
|
||||||
// experiment into a full-fledged CLI, literally overnight (as it it's 4:30am
|
console.error(cmd);
|
||||||
// right now), but I love what it accomplishes!
|
require('child_process').exec(cmd, function (err) {
|
||||||
|
if (err) {
|
||||||
/*global Promise*/
|
|
||||||
var fs = require('fs');
|
|
||||||
var Rasha = require('rasha');
|
|
||||||
var Eckles = require('eckles');
|
|
||||||
var Keypairs = require('../');
|
|
||||||
var pkg = require('../package.json');
|
|
||||||
|
|
||||||
var args = process.argv.slice(2);
|
|
||||||
var opts = { keys: [], jwts: [], jwss: [], payloads: [], names: [], filenames: [], files: [] };
|
|
||||||
var conflicts = {
|
|
||||||
'namedCurve': 'modulusLength'
|
|
||||||
, 'public': 'private'
|
|
||||||
};
|
|
||||||
Object.keys(conflicts).forEach(function (k) {
|
|
||||||
conflicts[conflicts[k]] = k;
|
|
||||||
});
|
|
||||||
function set(key, val) {
|
|
||||||
if (opts[conflicts[key]]) {
|
|
||||||
console.error("cannot set '" + key + "' to '" + val + "': '" + conflicts[key] + "' already set as '" + opts[conflicts[key]] + "'");
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
if (opts[key]) {
|
|
||||||
console.error("cannot set '" + key + "' to '" + val + "': already set as '" + opts[key] + "'");
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
opts[key] = val;
|
|
||||||
}
|
|
||||||
|
|
||||||
// duck type all the things
|
|
||||||
// TODO segment off by actions (gen, sign, verify) and allow parse/convert or gen before sign
|
|
||||||
args.forEach(function (arg) {
|
|
||||||
var larg = arg.toLowerCase().replace(/[^\w]/g, '');
|
|
||||||
var narg = parseInt(arg, 10) || 0;
|
|
||||||
if (narg.toString() !== arg) {
|
|
||||||
// i.e. 2048.pem is a valid file name
|
|
||||||
narg = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ('version' === arg) {
|
|
||||||
console.info(pkg.name, 'v' + pkg.version);
|
|
||||||
process.exit(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (setTimes(arg)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (setIssuer(arg)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (setSubject(arg)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ('ecdsa' === larg || 'ec' === larg) {
|
|
||||||
set('kty', "EC");
|
|
||||||
if (opts.modulusLength) {
|
|
||||||
console.error("EC keys do not have bit lengths such as '" + opts.modulusLength + "'. Choose either the P-256 or P-384 'curve' instead.");
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ('rsa' === larg) {
|
|
||||||
set('kty', "RSA");
|
|
||||||
if (opts.namedCurve) {
|
|
||||||
console.error("RSA keys do not have curves such as '" + opts.namedCurve + "'. Choose a modulus bit length, such as 2048 instead.");
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// P-384
|
|
||||||
if (-1 !== ['256', 'p256', 'prime256v1', 'secp256r1'].indexOf(larg)) {
|
|
||||||
set('namedCurve', "P-256");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// P-384
|
|
||||||
if (-1 !== ['384', 'p384', 'secp384r1'].indexOf(larg)) {
|
|
||||||
set('namedCurve', "P-384");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// RSA Modulus Length
|
|
||||||
if (narg) {
|
|
||||||
if (narg < 2048 || narg % 8 || narg > 8192) {
|
|
||||||
console.error("RSA modulusLength must be >=2048, <=8192 and divisible by 8");
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
set('modulusLength', narg);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Booleans
|
|
||||||
if (-1 !== [ 'private', 'public', 'nocompact', 'nofetch', 'debug', 'overwrite' ].indexOf(arg)) {
|
|
||||||
set(arg, true);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if ('uncompressed' === arg) {
|
|
||||||
set('uncompressed', true);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (-1 !== [ 'gen', 'sign', 'verify', 'decode' ].indexOf(arg)) {
|
|
||||||
set('action', arg);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Key format and encoding
|
|
||||||
if (-1 !== [ 'spki', 'pkix' ].indexOf(larg)) {
|
|
||||||
set('pubFormat', 'spki');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// TODO add ssh private key support (it's already built in jwk-to-ssh)
|
|
||||||
if ('ssh' === larg) {
|
|
||||||
set('pubFormat', 'ssh');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (-1 !== [ 'openssh', 'sec1', 'pkcs1', 'pkcs8' ].indexOf(larg)) {
|
|
||||||
// pkcs1 can be public or private, it's ambiguous
|
|
||||||
if (!opts.privFormat) {
|
|
||||||
set('privFormat', larg);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ('pkcs1' === larg || 'ssh' === larg) {
|
|
||||||
set('pubFormat', larg);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if ('openssh' === larg) {
|
|
||||||
console.warn("specifying 'openssh' twice? ...assuming that you meant 'ssh'");
|
|
||||||
set('pubFormat', 'ssh');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if ('pkcs8' === larg) {
|
|
||||||
console.warn("specifying 'pkcs8' twice? ...assuming that you meant 'spki' (pkix)");
|
|
||||||
set('pubFormat', 'spki');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if ('sec1' === larg) {
|
|
||||||
console.warn("specifying 'sec1' twice? ...assuming that you meant 'spki' (pkix)");
|
|
||||||
set('pubFormat', 'spki');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if ('jwk' === larg) {
|
|
||||||
if (!opts.privFormat) {
|
|
||||||
set('privFormat', larg);
|
|
||||||
} else {
|
|
||||||
set('pubFormat', larg);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if ('pem' === larg || 'der' === larg || 'json' === larg) {
|
|
||||||
if (!opts.privEncoding) {
|
|
||||||
set('privEncoding', larg);
|
|
||||||
} else {
|
|
||||||
set('pubEncoding', larg);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Filename
|
|
||||||
try {
|
|
||||||
fs.accessSync(arg);
|
|
||||||
opts.filenames.push(arg);
|
|
||||||
opts.names.push({ taken: true, name: arg });
|
|
||||||
if (!guessFile(arg)) {
|
|
||||||
opts.files.push(arg);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
} catch(e) { /* not keypath */ }
|
|
||||||
|
|
||||||
// Test for JWK-ness / payload-ness
|
|
||||||
if (guess(arg)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Test for JWT-ness
|
|
||||||
if (setJwt(arg)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Possibly the output file
|
|
||||||
if (opts.names.length < 3) {
|
|
||||||
opts.names.push({ taken: false, name: arg });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// check if it's a valid output key
|
|
||||||
|
|
||||||
console.error("too many arguments or didn't understand argument '" + arg + "'");
|
|
||||||
if (opts.debug) {
|
|
||||||
console.warn(opts);
|
|
||||||
}
|
|
||||||
process.exit(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
function guessFile(filename) {
|
|
||||||
try {
|
|
||||||
// TODO der support
|
|
||||||
var txt = fs.readFileSync(filename).toString('utf8');
|
|
||||||
return guess(txt, filename);
|
|
||||||
} catch(e) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function guess(txt, filename) {
|
|
||||||
try {
|
|
||||||
var json = JSON.parse(txt);
|
|
||||||
if (-1 !== [ 'RSA', 'EC' ].indexOf(json.kty)) {
|
|
||||||
opts.keys.push({ raw: txt, jwk: json, filename: filename });
|
|
||||||
return true;
|
|
||||||
} else if (json.signature && json.payload && (json.header || json.protected)) {
|
|
||||||
opts.jwss.push(json);
|
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
opts.payloads.push(txt);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
} catch(e) {
|
|
||||||
try {
|
|
||||||
var jwk = Eckles.importSync({ pem: txt });
|
|
||||||
// pem._string = txt;
|
|
||||||
opts.keys.push({ jwk: jwk, pem: true, raw: txt });
|
|
||||||
return true;
|
|
||||||
} catch(e) {
|
|
||||||
try {
|
|
||||||
var jwk = Rasha.importSync({ pem: txt });
|
|
||||||
// pem._string = txt;
|
|
||||||
opts.keys.push({ jwk: jwk, pem: true, raw: txt });
|
|
||||||
return true;
|
|
||||||
} catch(e) {
|
|
||||||
// ignore
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// node bin/keypairs.js debug spki pem json pkcs1 ~/.ssh/id_rsa.pub foo.pem bar.pem 'abc.abc.abc' '{"kty":"EC"}' '{}' '{"signature":"x", "payload":"x", "header":"x"}' '{"signature":"x", "payload":"x", "protected":"x"}' verify
|
|
||||||
if (opts.debug) {
|
|
||||||
console.warn(opts);
|
|
||||||
}
|
|
||||||
|
|
||||||
var kp;
|
|
||||||
|
|
||||||
if ('gen' === opts.action || (!opts.action && !opts.names.length)) {
|
|
||||||
if (opts.names.length > 2) {
|
|
||||||
console.error("there should only be two output files at most when generating keypairs");
|
|
||||||
console.error(opts.names.map(function (t) { return t.name; }));
|
|
||||||
process.exit(1);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
kp = genKeypair();
|
|
||||||
} else if ('decode' === opts.action) {
|
|
||||||
if (!opts.jwts.length) {
|
|
||||||
console.error("no JWTs specified to decode");
|
|
||||||
process.exit(1);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
return Promise.all(opts.jwts.map(function (jwt, i) {
|
|
||||||
try {
|
|
||||||
var decoded = decodeJwt(jwt);
|
|
||||||
console.info("Decoded #" + (i + 1) + ":");
|
|
||||||
console.info(JSON.stringify(decoded, null, 2));
|
|
||||||
} catch(e) {
|
|
||||||
console.error("Failed to decode #" + (i + 1) + ":");
|
|
||||||
console.error(e);
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
} else if ('verify' === opts.action || (!opts.action && opts.jwts.length)) {
|
|
||||||
if (!opts.jwts.length) {
|
|
||||||
console.error("no JWTs specified to verify");
|
|
||||||
process.exit(1);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
return Promise.all(opts.jwts.map(function (jwt, i) {
|
|
||||||
return require('keyfetch').verify({ jwt: jwt }).then(function (decoded) {
|
|
||||||
console.info("Verified #" + (i + 1) + ":");
|
|
||||||
console.info(JSON.stringify(decoded, null, 2));
|
|
||||||
}).catch(function (err) {
|
|
||||||
console.error("Failed to verify #" + (i + 1) + ":");
|
|
||||||
console.error(err);
|
console.error(err);
|
||||||
});
|
|
||||||
}));
|
|
||||||
} else {
|
|
||||||
if (opts.names.length > 3) {
|
|
||||||
console.error("there should only be one input file and up to two output files when converting keypairs");
|
|
||||||
console.error(opts.names.map(function (t) { return t.name; }));
|
|
||||||
process.exit(1);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
var pair = readKeypair();
|
console.info("Run 'keypairs help' to see what you can do!");
|
||||||
pair._convert = true;
|
|
||||||
kp = Promise.resolve(pair);
|
|
||||||
}
|
|
||||||
|
|
||||||
if ('sign' === opts.action) {
|
|
||||||
return kp.then(function (pair) {
|
|
||||||
var jwk = pair.private;
|
|
||||||
if (!jwk || !jwk.d) {
|
|
||||||
console.error("the first key was not a private key");
|
|
||||||
console.error(opts.names.map(function (t) { return t.name; }));
|
|
||||||
process.exit(1);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!opts.payloads.length) {
|
|
||||||
opts.payloads.push('{}');
|
|
||||||
}
|
|
||||||
return Promise.all(opts.payloads.map(function (payload) {
|
|
||||||
var claims = JSON.parse(payload);
|
|
||||||
if (!claims.iss) { claims.iss = opts.issuer; }
|
|
||||||
if (!claims.iss) { console.warn("No issuer given, token will not be verifiable"); }
|
|
||||||
if (!claims.sub) { claims.sub = opts.sub; }
|
|
||||||
if (!claims.exp) {
|
|
||||||
if (!opts.expiresAt) { setTimes('15m'); }
|
|
||||||
claims.exp = opts.expiresAt;
|
|
||||||
}
|
|
||||||
if (!claims.iat) { claims.iat = opts.issuedAt; }
|
|
||||||
if (!claims.nbf) { claims.nbf = opts.nbf; }
|
|
||||||
return Keypairs.signJwt({ jwk: pair.private, claims: claims }).then(function (jwt) {
|
|
||||||
console.info(jwt);
|
|
||||||
});
|
});
|
||||||
}));
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
return kp.then(function (pair) {
|
|
||||||
if (pair._convert) {
|
|
||||||
return convertKeypair(pair);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function readKeypair() {
|
|
||||||
// note that the jwk may be a string
|
|
||||||
var keyopts = opts.keys.shift();
|
|
||||||
var jwk = keyopts && keyopts.jwk;
|
|
||||||
if (!jwk) {
|
|
||||||
console.error("no keys could be parsed from the given arguments");
|
|
||||||
console.error(opts.names.map(function (t) { return t.name; }));
|
|
||||||
process.exit(1);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// omit the primary private key from the list of actual (or soon-to-be) files
|
|
||||||
if (keyopts.filename) {
|
|
||||||
opts.names = opts.names.filter(function (name) {
|
|
||||||
return name.name !== keyopts.filename;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
var pair = { private: null, public: null, pem: keyopts.pem, raw: keyopts.raw };
|
|
||||||
if (jwk.d) {
|
|
||||||
pair.private = jwk;
|
|
||||||
}
|
|
||||||
pair.public = Keypairs._neuter({ jwk: jwk });
|
|
||||||
return pair;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Note: some of the conditions can be factored out
|
|
||||||
// this was all built in high-speed iterative during the 3ams+
|
|
||||||
function convertKeypair(pair) {
|
|
||||||
//var pair = readKeypair();
|
|
||||||
|
|
||||||
var ps = [];
|
|
||||||
// if it's private only, or if it's not public-only, produce the private key
|
|
||||||
if (pair.private || !opts.public) {
|
|
||||||
// if it came from pem (or is explicitly json), it should go to jwk
|
|
||||||
// otherwise, if it came from jwk, it should go to pem
|
|
||||||
if (((!opts.privEncoding && pair.pem) || 'json' === opts.privEncoding)
|
|
||||||
&& ((!opts.privFormat && pair.pem) || 'jwk' === opts.privFormat)) {
|
|
||||||
ps.push(Promise.resolve(pair.private));
|
|
||||||
} else {
|
|
||||||
ps.push(Keypairs.export({ jwk: pair.private, format: opts.privFormat, encoding: opts.privEncoding }));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// if it's not private key only, we want to produce the public key
|
|
||||||
if (!opts.private) {
|
|
||||||
if (opts.public) {
|
|
||||||
// if it's public-only the ambigious options will fall to the private key
|
|
||||||
// so we need to fix that
|
|
||||||
if (!opts.pubFormat) { opts.pubFormat = opts.privFormat; }
|
|
||||||
if (!opts.pubEncoding) { opts.pubEncoding = opts.privEncoding; }
|
|
||||||
}
|
|
||||||
|
|
||||||
// same as above - swap formats by default
|
|
||||||
if (((!opts.pubEncoding && pair.pem) || 'json' === opts.pubEncoding)
|
|
||||||
&& ((!opts.pubFormat && pair.pem) || 'jwk' === opts.pubFormat)) {
|
|
||||||
ps.push(Promise.resolve(pair.public));
|
|
||||||
} else {
|
|
||||||
ps.push(Keypairs.export({ jwk: pair.public, format: opts.pubFormat, encoding: opts.pubEncoding, public: true }));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return Promise.all(ps).then(function (exported) {
|
|
||||||
// start with the first key, annotating if it should be public
|
|
||||||
var index = 0;
|
|
||||||
var key = stringifyIfJson(index, opts.public);
|
|
||||||
|
|
||||||
// re: opts.names
|
|
||||||
// if we're only doing the public key we can end early
|
|
||||||
// (if the source key was from a file and was in opts.names,
|
|
||||||
// we're safe here because we already removed it earlier)
|
|
||||||
|
|
||||||
if (opts.public) {
|
|
||||||
if (opts.names.length) {
|
|
||||||
writeFile(opts.names[index].name, key, !opts.public);
|
|
||||||
} else {
|
|
||||||
// output public keys to stderr
|
|
||||||
printPublic(key);
|
|
||||||
}
|
|
||||||
// end <-- we're not outputting other keys
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// private key stuff
|
|
||||||
if (opts.names.length >= 1) {
|
|
||||||
writeFile(opts.names[index].name, key, true);
|
|
||||||
} else {
|
|
||||||
printPrivate(key);
|
|
||||||
}
|
|
||||||
|
|
||||||
// pub key stuff
|
|
||||||
// we have to output the private key,
|
|
||||||
// but the public key can be derived at any time
|
|
||||||
// so we don't need to put the same noise to the screen
|
|
||||||
if (!opts.private && opts.names.length >= 2) {
|
|
||||||
index = 1;
|
|
||||||
key = stringifyIfJson(index, false);
|
|
||||||
writeFile(opts.names[index].name, key, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
return pair;
|
|
||||||
|
|
||||||
function stringifyIfJson(i, pub) {
|
|
||||||
if (exported[i].kty) {
|
|
||||||
if (pub) {
|
|
||||||
if (opts.expiresAt) { exported[i].exp = opts.expiresAt; }
|
|
||||||
exported[i].use = "sig";
|
|
||||||
}
|
|
||||||
exported[i] = JSON.stringify(exported[i]);
|
|
||||||
}
|
|
||||||
return exported[i];
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function genKeypair() {
|
|
||||||
return Keypairs.generate({
|
|
||||||
kty: opts.kty
|
|
||||||
, modulusLength: opts.modulusLength
|
|
||||||
, namedCurve: opts.namedCurve
|
|
||||||
}).then(function (pair) {
|
|
||||||
// always generate as jwk by default
|
|
||||||
var ps = [];
|
|
||||||
if ((!opts.privEncoding || 'json' === opts.privEncoding) && (!opts.privFormat || 'jwk' === opts.privFormat)) {
|
|
||||||
ps.push(Promise.resolve(pair.private));
|
|
||||||
} else {
|
|
||||||
ps.push(Keypairs.export({ jwk: pair.private, format: opts.privFormat, encoding: opts.privEncoding }));
|
|
||||||
}
|
|
||||||
if ((!opts.pubEncoding || 'json' === opts.pubEncoding) && (!opts.pubFormat || 'jwk' === opts.pubFormat)) {
|
|
||||||
ps.push(Promise.resolve(pair.public));
|
|
||||||
} else {
|
|
||||||
ps.push(Keypairs.export({ jwk: pair.public, format: opts.pubFormat, encoding: opts.pubEncoding, public: true }));
|
|
||||||
}
|
|
||||||
return Promise.all(ps).then(function (arr) {
|
|
||||||
if (arr[0].kty) {
|
|
||||||
arr[0] = JSON.stringify(arr[0]);
|
|
||||||
}
|
|
||||||
if (arr[1].kty) {
|
|
||||||
if (opts.expiresAt) { arr[1].exp = opts.expiresAt; }
|
|
||||||
arr[1].use = "sig";
|
|
||||||
arr[1] = JSON.stringify(arr[1]);
|
|
||||||
}
|
|
||||||
if (!opts.names.length) {
|
|
||||||
console.info(arr[0] + "\n");
|
|
||||||
console.warn(arr[1] + "\n");
|
|
||||||
}
|
|
||||||
if (opts.names.length >= 1) {
|
|
||||||
writeFile(opts.names[0].name, arr[0], true);
|
|
||||||
if (!opts.private && opts.names.length >= 2) {
|
|
||||||
writeFile(opts.names[1].name, arr[1]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return pair;
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function writeFile(name, key, priv) {
|
|
||||||
var overwrite;
|
|
||||||
try {
|
|
||||||
fs.accessSync(name);
|
|
||||||
overwrite = opts.overwrite;
|
|
||||||
if (!opts.overwrite) {
|
|
||||||
if (priv) {
|
|
||||||
// output private keys to stdout
|
|
||||||
console.info(key + "\n");
|
|
||||||
} else {
|
|
||||||
// output public keys to stderr
|
|
||||||
console.warn(key + "\n");
|
|
||||||
}
|
|
||||||
console.error("'" + name + "' exists! force overwrite with 'overwrite'");
|
|
||||||
process.exit(1);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
} catch(e) {
|
|
||||||
// the file does not exist (or cannot be accessed)
|
|
||||||
}
|
|
||||||
fs.writeFileSync(name, key);
|
|
||||||
if (overwrite) {
|
|
||||||
console.info("Overwrote " + (priv ? "private" : "public") + " key at '" + name + "'");
|
|
||||||
} else {
|
|
||||||
console.info("Wrote " + (priv ? "private" : "public") + " key to '" + name + "'");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function setJwt(arg) {
|
|
||||||
try {
|
|
||||||
var jwt = arg.match(/^([\w-]+)\.([\w-]+)\.([\w-]+)$/);
|
|
||||||
// make sure header is a JWT header
|
|
||||||
JSON.parse(Buffer.from(jwt[1], 'base64'));
|
|
||||||
opts.jwts.push(arg);
|
|
||||||
return true;
|
|
||||||
} catch(e) {
|
|
||||||
// ignore
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function setSubject(arg) {
|
|
||||||
if (!/.+@[a-z0-9_-]+\.[a-z0-9_-]+/i.test(arg)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
opts.subject = arg;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
function setIssuer(arg) {
|
|
||||||
if (!/^https?:\/\/[a-z0-9_-]+\.[a-z0-9_-]+/i.test(arg)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
new URL(arg);
|
|
||||||
opts.issuer = arg.replace(/\/$/, '');
|
|
||||||
return true;
|
|
||||||
} catch(e) {
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
function setTimes(arg) {
|
|
||||||
var t = arg.match(/^(\-?\d+)([dhms])$/i);
|
|
||||||
if (!t || !t[0]) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
var num = parseInt(t[1], 10);
|
|
||||||
var unit = t[2];
|
|
||||||
var mult = 1;
|
|
||||||
opts.issuedAt = Math.round(Date.now()/1000);
|
|
||||||
switch(unit) {
|
|
||||||
// fancy fallthrough, what fun!
|
|
||||||
case 'd':
|
|
||||||
mult *= 24;
|
|
||||||
/*falls through*/
|
|
||||||
case 'h':
|
|
||||||
mult *= 60;
|
|
||||||
/*falls through*/
|
|
||||||
case 'm':
|
|
||||||
mult *= 60;
|
|
||||||
/*falls through*/
|
|
||||||
case 's':
|
|
||||||
mult *= 1;
|
|
||||||
}
|
|
||||||
if (!opts.expiresIn) {
|
|
||||||
opts.expiresIn = mult * num;
|
|
||||||
opts.expiresAt = opts.issuedAt + opts.expiresIn;
|
|
||||||
} else {
|
|
||||||
opts.nbf = opts.issuedAt + (mult * num);
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
function decodeJwt(jwt) {
|
|
||||||
var parts = jwt.split('.');
|
|
||||||
return {
|
|
||||||
header: JSON.parse(Buffer.from(parts[0], 'base64'))
|
|
||||||
, payload: JSON.parse(Buffer.from(parts[1], 'base64'))
|
|
||||||
, signature: parts[2] //Buffer.from(parts[2], 'base64')
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function printPrivate(key) {
|
|
||||||
console.info(key + "\n");
|
|
||||||
}
|
|
||||||
function printPublic(key) {
|
|
||||||
console.warn(key + "\n");
|
|
||||||
}
|
|
||||||
|
162
keypairs.js
162
keypairs.js
@ -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,6 +33,7 @@ Keypairs.parse = function (opts) {
|
|||||||
var pem;
|
var pem;
|
||||||
var p;
|
var p;
|
||||||
|
|
||||||
|
if (!opts.key || !opts.key.kty) {
|
||||||
try {
|
try {
|
||||||
jwk = JSON.parse(opts.key);
|
jwk = JSON.parse(opts.key);
|
||||||
p = Keypairs.export({ jwk: jwk }).catch(function (e) {
|
p = Keypairs.export({ jwk: jwk }).catch(function (e) {
|
||||||
@ -41,6 +51,9 @@ Keypairs.parse = function (opts) {
|
|||||||
return Promise.reject(err);
|
return Promise.reject(err);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
p = Promise.resolve(opts.key);
|
||||||
|
}
|
||||||
|
|
||||||
return p.then(function (jwk) {
|
return p.then(function (jwk) {
|
||||||
var pubopts = JSON.parse(JSON.stringify(opts));
|
var pubopts = JSON.parse(JSON.stringify(opts));
|
||||||
@ -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;
|
||||||
|
});
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -87,24 +105,32 @@ Keypairs.export = function (opts) {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
Keypairs._neuter = function (opts) {
|
// Chopping off the private parts is now part of the public API.
|
||||||
|
// I thought it sounded a little too crude at first, but it really is the best name in every possible way.
|
||||||
|
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]));
|
||||||
});
|
});
|
||||||
return jwk;
|
return jwk;
|
||||||
};
|
};
|
||||||
|
|
||||||
Keypairs.publish = function (opts) {
|
Keypairs.publish = function (opts) {
|
||||||
if ('object' !== typeof opts.jwk || !opts.jwk.kty) { throw new Error("invalid jwk: " + JSON.stringify(opts.jwk)); }
|
if ('object' !== typeof opts.jwk || !opts.jwk.kty) { throw new Error("invalid jwk: " + JSON.stringify(opts.jwk)); }
|
||||||
|
|
||||||
var jwk = Keypairs._neuter(opts);
|
// returns a copy
|
||||||
|
var jwk = Keypairs.neuter(opts);
|
||||||
|
|
||||||
if (!jwk.exp) {
|
if (jwk.exp) {
|
||||||
if (opts.expiresIn) { jwk.exp = Math.round(Date.now()/1000) + opts.expiresIn; }
|
jwk.exp = setTime(jwk.exp);
|
||||||
else { jwk.exp = opts.expiresAt; }
|
} else {
|
||||||
|
if (opts.exp) { jwk.exp = setTime(opts.exp); }
|
||||||
|
else if (opts.expiresIn) { jwk.exp = Math.round(Date.now()/1000) + opts.expiresIn; }
|
||||||
|
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"; }
|
||||||
|
|
||||||
@ -128,20 +154,25 @@ 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 (false === claims.iat) {
|
if (!claims.iat && (false === claims.iat || false === opts.iat)) {
|
||||||
claims.iat = undefined;
|
claims.iat = undefined;
|
||||||
} else if (!claims.iat) {
|
} else if (!claims.iat) {
|
||||||
claims.iat = Math.round(Date.now()/1000);
|
claims.iat = Math.round(Date.now()/1000);
|
||||||
}
|
}
|
||||||
if (false === claims.exp) {
|
|
||||||
|
if (opts.exp) {
|
||||||
|
claims.exp = setTime(opts.exp);
|
||||||
|
} else if (!claims.exp && (false === claims.exp || false === opts.exp)) {
|
||||||
claims.exp = undefined;
|
claims.exp = undefined;
|
||||||
} else if (!claims.exp) {
|
} else if (!claims.exp) {
|
||||||
throw new Error("opts.claims.exp should be the expiration date (as seconds since the Unix epoch) or false");
|
throw new Error("opts.claims.exp should be the expiration date as seconds, human form (i.e. '1h' or '15m') or false");
|
||||||
}
|
}
|
||||||
if (false === claims.iss) {
|
|
||||||
|
if (opts.iss) { claims.iss = opts.iss; }
|
||||||
|
if (!claims.iss && (false === claims.iss || false === opts.iss)) {
|
||||||
claims.iss = undefined;
|
claims.iss = undefined;
|
||||||
} else if (!claims.iss) {
|
} else if (!claims.iss) {
|
||||||
throw new Error("opts.claims.iss should be in the form of https://example.com/, a secure OIDC base url");
|
throw new Error("opts.claims.iss should be in the form of https://example.com/, a secure OIDC base url");
|
||||||
@ -166,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) {
|
||||||
@ -198,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, '')
|
||||||
@ -218,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 {
|
||||||
@ -226,6 +300,36 @@ Keypairs.signJws = function (opts) {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function setTime(time) {
|
||||||
|
if ('number' === typeof time) { return time; }
|
||||||
|
|
||||||
|
var t = time.match(/^(\-?\d+)([dhms])$/i);
|
||||||
|
if (!t || !t[0]) {
|
||||||
|
throw new Error("'" + time + "' should be datetime in seconds or human-readable format (i.e. 3d, 1h, 15m, 30s");
|
||||||
|
}
|
||||||
|
|
||||||
|
var now = Math.round(Date.now()/1000);
|
||||||
|
var num = parseInt(t[1], 10);
|
||||||
|
var unit = t[2];
|
||||||
|
var mult = 1;
|
||||||
|
switch(unit) {
|
||||||
|
// fancy fallthrough, what fun!
|
||||||
|
case 'd':
|
||||||
|
mult *= 24;
|
||||||
|
/*falls through*/
|
||||||
|
case 'h':
|
||||||
|
mult *= 60;
|
||||||
|
/*falls through*/
|
||||||
|
case 'm':
|
||||||
|
mult *= 60;
|
||||||
|
/*falls through*/
|
||||||
|
case 's':
|
||||||
|
mult *= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return now + (mult * num);
|
||||||
|
}
|
||||||
|
|
||||||
Enc.strToUrlBase64 = function (str) {
|
Enc.strToUrlBase64 = function (str) {
|
||||||
// node automatically can tell the difference
|
// node automatically can tell the difference
|
||||||
// between uc2 (utf-8) strings and binary strings
|
// between uc2 (utf-8) strings and binary strings
|
||||||
@ -238,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);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
13
package.json
13
package.json
@ -1,17 +1,16 @@
|
|||||||
{
|
{
|
||||||
"name": "keypairs",
|
"name": "keypairs",
|
||||||
"version": "1.2.5",
|
"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": [
|
||||||
"CLI.md",
|
|
||||||
"bin/keypairs.js"
|
"bin/keypairs.js"
|
||||||
],
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "node test.js"
|
"test": "node test.js"
|
||||||
},
|
},
|
||||||
"bin": {
|
"bin": {
|
||||||
"keypairs": "bin/keypairs.js"
|
"keypairs-install": "bin/keypairs.js"
|
||||||
},
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
@ -22,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",
|
||||||
|
15
test.js
15
test.js
@ -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,6 +91,20 @@ 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, alg: 'ES512', iss: 'https://example.com/', exp: '1h' }).then(function (jwt) {
|
||||||
|
var parts = jwt.split('.');
|
||||||
|
var now = Math.round(Date.now()/1000);
|
||||||
|
var token = {
|
||||||
|
header: JSON.parse(Buffer.from(parts[0], 'base64'))
|
||||||
|
, payload: JSON.parse(Buffer.from(parts[1], 'base64'))
|
||||||
|
, signature: parts[2] //Buffer.from(parts[2], 'base64')
|
||||||
|
};
|
||||||
|
// allow some leeway just in case we happen to hit a 1ms boundary
|
||||||
|
if (token.payload.exp - now > 60 * 59.99) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
throw new Error("token was not properly generated");
|
||||||
|
})
|
||||||
]).then(function (results) {
|
]).then(function (results) {
|
||||||
if (results.length && results.every(function (v) { return true === v; })) {
|
if (results.length && results.every(function (v) { return true === v; })) {
|
||||||
console.info("If a warning prints right above this, it's a pass");
|
console.info("If a warning prints right above this, it's a pass");
|
||||||
|
Loading…
x
Reference in New Issue
Block a user