diff --git a/lib/keypairs.js b/lib/keypairs.js index e4fc43b..08d30c2 100644 --- a/lib/keypairs.js +++ b/lib/keypairs.js @@ -6,6 +6,9 @@ var keypairs = module.exports; var PEM = require('./pem-parser.js'); PEM.packBlock = require('./pem-packer.js').packBlock; +var crypto = require('./crypto.js'); +var Enc = require('./encoding.js'); + var ASN1 = require('./asn1-parser.js'); ASN1.pack = require('./asn1-packer.js').pack; @@ -15,11 +18,45 @@ var SSH = require('./ssh-parser.js'); SSH.pack = require('./ssh-packer.js').pack; // sign, signJws, signJwt +/* var JWS = require('./jws.js'); var JWT = require('./jwt.js'); +*/ -var RSA = require('./rsa.js'); -var EC = require('./ec.js'); +keypairs.signJws = function (opts) { + opts = JSON.stringify(JSON.parse(opts)); + if (!opts.header) { opts.header = {}; } + if (!opts.protected) { opts.protected = {}; } + if (!opts.payload) { opts.payload = {}; } + var protect = Enc.binToBase64(JSON.stringify(opts.protected)); + var payload = Enc.binToBase64(JSON.stringify(opts.payload)); + if (!opts.jwt) { opts.jwt = keypairs.import(opts).jwt; } + opts.header.typ = 'JWT'; + opts.header.alg = ('RSA' === opts.jwk) ? 'RS256' : 'ES256'; + // key, jwk, pem, der + return crypto.sign(opts, Enc.binToBuf(protect + '.' + payload), 'SHA256').then(function (sig) { + return { + header: opts.header + , protected: protect + , payload: payload + , signature: sig + }; + }); +}; + +keypairs.signJwt = function (opts) { + opts = JSON.stringify(JSON.parse(opts)); + if (!opts.header) { opts.header = {}; } + if (!opts.payload) { opts.payload = {}; } + var protect = Enc.binToBase64(JSON.stringify(opts.header)) + '.' + + Enc.binToBase64(JSON.stringify(opts.payload)); + if (!opts.jwt) { opts.jwt = keypairs.import(opts).jwt; } + opts.header.alg = ('RSA' === opts.jwk) ? 'RS256' : 'ES256'; + // key, jwk, pem, der + return crypto.sign(opts, Enc.binToBuf(protect), 'SHA256').then(function (sig) { + return protect + '.' + sig; + }); +}; keypairs.import = function (opts) { return Promise.resolve().then(function () { @@ -30,7 +67,7 @@ keypairs.import = function (opts) { if (opts.pem) { pem = PEM.parseBlock(opts.pem); - if (/OPENSSH/.test(pem.type)) { + if ('OPENSSH PRIVATE KEY' === pem.type) { jwk = SSH.parse(pem); } else { der = pem.bytes;