'Return an encoded claim set': function(test) { test.expect(1); var header = { alg: 'RS256', typ: 'JWT' }; var claim = { iss: '*****@*****.**', scope: 'https://www.googleapis.com/auth/devstorage.readonly', aud: 'https://accounts.google.com/o/oauth2/token', exp: 1328554385, iat: 1328550785 }; var headerEncoded = base64url(JSON.stringify(header)), claimEncoded = base64url(JSON.stringify(claim)); var sign = crypto.createSign('sha256WithRSAEncryption'); sign.update(headerEncoded + '.' + claimEncoded); var signature = sign.sign(_pair.privateKey); var signatureEncoded = base64url(signature); var token = new Token('*****@*****.**'); token.makeJwt(claim, '*****@*****.**'). then(function(jwt) { test.equal(jwt, headerEncoded + '.' + claimEncoded + '.' + signatureEncoded); test.done(); }). catch(function(err) { console.log(err); test.ok(false, err); test.done(); }); },
exports.getPlugins = async function () { if (plugins[0]) return plugins const secretA = base64url(crypto.randomBytes(32)) const secretB = base64url(crypto.randomBytes(32)) plugins[0] = new PluginVirtual({ currencyCode: 'USD', currencyScale: 6, maxBalance: '1000', secret: secretA, peerPublicKey: Token.publicKey(secretB), rpcUri: 'http://localhost:' + port + '/pluginB', _store: new ObjStore() }) plugins[1] = new PluginVirtual({ currencyCode: 'USD', currencyScale: 6, maxBalance: '1000', secret: secretB, peerPublicKey: Token.publicKey(secretA), rpcUri: 'http://localhost:' + port + '/pluginA', _store: new ObjStore() }) return plugins }
function jwsSecuredInput(header, payload, opts) { const encodedHeader = base64url(toString(header)); const encodedPayload = header.typ === 'JWT' || opts.json ? base64url(JSON.stringify(payload)) : base64url(toString(payload)); return util.format('%s.%s', encodedHeader, encodedPayload); }
JWT.prototype.encode = function (secret) { // JWT Spec requires valid payload, header and supported algortitm // If this method is invoked on an instance, all of these properties // should be pre-validated by the constructor. // initialize the components var headerB64u = this.headerB64u , payloadB64u = base64url(JSON.stringify(this.payload)) , input = headerB64u + '.' + payloadB64u , algorithm = this.header.alg , signature ; // Plaintext if (algorithm === 'none') { signature = ''; } // JWE else if (this.header.enc) { // make a JWE } // JWS else { this.signature = signature = jwa(algorithm).sign(input, secret); } return input + '.' + base64url(signature); };
function jwsOutput(header, payload, signature) { return util.format( '%s.%s.%s', base64url(header), base64url(payload), signature); }
function generateToken () { let parts = [ base64URL(crypto.randomBytes(28)), base64URL('' + Date.now()), base64URL(crypto.randomBytes(36)) ] return R.join('-', parts) }
function (c) { client = c return client.updateDevice({ name: 'baz', type: 'mobile', pushCallback: 'https://example.com/qux', pushPublicKey: base64url(Buffer.concat([new Buffer('\x04'), crypto.randomBytes(64)])), pushAuthKey: base64url(crypto.randomBytes(16)) }) }
function (t) { var email = server.uniqueEmail() var newPassword = '******' var client return Client.createAndVerify(config.publicUrl, email, 'bar', server.mailbox, { device: { name: 'baz', type: 'mobile', pushCallback: 'https://example.com/qux', pushPublicKey: base64url(Buffer.concat([new Buffer('\x04'), crypto.randomBytes(64)])), pushAuthKey: base64url(crypto.randomBytes(16)) } }) .then( function (c) { client = c return client.devices() } ) .then( function (devices) { t.equal(devices.length, 1, 'devices list contains 1 item') } ) .then( function () { return client.forgotPassword() } ) .then( function () { return server.mailbox.waitForCode(email) } ) .then( function (code) { return resetPassword(client, code, newPassword) } ) .then( function () { return Client.login(config.publicUrl, email, newPassword) } ) .then( function (client) { return client.devices() } ) .then( function (devices) { t.equal(devices.length, 0, 'devices list is empty') } ) }
verifyToken: function verifyToken(req, res, next) { var token = req.get('Authentification'); if (!token) { token = req.query.token; } var tokenValidate = false; if (token === "null" || !token) { res.status(400).send('No token'); return; } var tokenTab = token.split("."); if (tokenTab.length != 3) { res.status(400).send('Invalid token'); return; } var signature = crypto.createHmac("SHA256", config.key).update(tokenTab[0] + "." + tokenTab[1]).digest("bin"); if (base64url(signature) != tokenTab[2]) { res.status(400).send('Invalid token'); return; } var payloadDecode = base64url.decode(tokenTab[1]); if (Date.now() > JSON.parse(payloadDecode).exp) { res.status(400).send('Token date expirated'); return; } req.email = JSON.parse(payloadDecode).email; req.idUser = JSON.parse(payloadDecode).id; next(); },
resetPassword: function () { // request password reset this.reset.token = base64url(crypto.randomBytes(20)); const tomorrow = +new Date() + (60 * 60 * 24 * 1000); this.reset.expires = tomorrow; },
const hmac = (key, data) => { return base64url( crypto.createHmac('sha256', key) .update(data, 'ascii') .digest() ) }
const publicKey = (seed) => { // seed should be a base64url string const seedBuffer = base64url.toBuffer(seed) return base64url(tweetnacl.scalarMult.base( crypto.createHash('sha256').update(seedBuffer).digest() )) }
function (t) { var email = server.uniqueEmail() var password = '******' var deviceInfo = { name: 'test device', type: 'desktop', pushCallback: 'https://foo/bar', pushPublicKey: base64url(Buffer.concat([new Buffer('\x04'), crypto.randomBytes(64)])), pushAuthKey: base64url(crypto.randomBytes(16)) } return Client.create(config.publicUrl, email, password) .then( function (client) { return client.updateDevice(deviceInfo) .then( function () { return client.devices() } ) .then( function (devices) { t.equal(devices[0].pushCallback, deviceInfo.pushCallback, 'devices returned correct pushCallback') t.equal(devices[0].pushPublicKey, deviceInfo.pushPublicKey, 'devices returned correct pushPublicKey') t.equal(devices[0].pushAuthKey, deviceInfo.pushAuthKey, 'devices returned correct pushAuthKey') return client.updateDevice({ id: client.device.id, pushCallback: 'https://bar/foo' }) } ) .then( function () { return client.devices() } ) .then( function (devices) { t.equal(devices[0].pushCallback, 'https://bar/foo', 'devices returned correct pushCallback') t.equal(devices[0].pushPublicKey, '', 'devices returned newly empty pushPublicKey') t.equal(devices[0].pushAuthKey, '', 'devices returned newly empty pushAuthKey') } ) } ) }
dgst.on('exit', function (code) { if (code !== 0) return t.fail('could not test interop: openssl failure'); const sig = base64url(buffer); t.ok(algo.verify(input, sig, rsaPublicKey), 'should verify'); t.notOk(algo.verify(input, sig, rsaWrongPublicKey), 'should not verify'); t.end(); });
.then(function(repo) { repoUrl = repo; var clone = options.clone; if (!clone) { clone = path.join(getCacheDir(), base64url(repo)); } log('Cloning %s into %s', repo, clone); return Git.clone(repo, clone, options.branch, options); })
const tokenFromSharedSecret = (sharedSecretBuffer) => { // token is created by feeding the string 'token' into // an HMAC, using the shared secret as the key. return base64url( crypto.createHmac('sha256', sharedSecretBuffer) .update(TOKEN_HMAC_INPUT, 'ascii') .digest() ) }
(c) => { client = c; return client.updateDevice({ name: 'baz', type: 'mobile', pushCallback: 'https://updates.push.services.mozilla.com/qux', pushPublicKey: mocks.MOCK_PUSH_KEY, pushAuthKey: base64url(crypto.randomBytes(16)) }); }
onCardAnswered(answer: AnswerMessage) { if (answer.isValid) { this.rightAudio.play(); } else { const { card } = answer; const mediaUrlForCard = `https://s3.eu-central-1.amazonaws.com/recallq-sounds/${base64url(card.answer.contentWithArticle)}.mp3`; const audio = new Audio(mediaUrlForCard); audio.play(); } }
function generateToken(size, expiresIn) { var r = crypto.randomBytes(size); var r = generateId(); var d = Date.now() + (expiresIn || 0); var s = r + '.' + d; console.warn('s: ', s); var t = base64url(s); console.warn('t: ', t); return t; }
generate: function (user) { var header = { alg: "HS256", typ: "JWT" }; var payload = { id: user.id, email: user.email, exp : Date.now() + 10000* 60 * 2 * 60 * 1000 //temps d'expiration : 120min }; var signature = crypto.createHmac("SHA256", config.key).update(base64url(JSON.stringify(header)) + "." + base64url(JSON.stringify(payload))).digest("bin"); return base64url(JSON.stringify(header)) + "." + base64url(JSON.stringify(payload)) + "." + base64url(signature); },
function newUrlSafeGuid(bytes, matcher) { // generate ids until we get a unique one (base64 should prevent collision problems) var id; do { id = base64url(crypto.randomBytes(bytes)); } while(matcher(id)); return id; };
/** * exportKey * * @description * * @param {string} format * @param {CryptoKey} key * * @returns {*} */ exportKey (format, key) { let result, data // 1. Validate handle slot if (!key.handle) { throw new OperationError('Missing key material') } // 2.1 "raw" format if (format === 'raw'){ // 2.1.1 Let data be the raw octets of the key data = key.handle // 2.1.2 Let result be containing data result = Buffer.from(data) } // 2.2 "jwk" format else if (format === 'jwk'){ // 2.2.1 Validate JsonWebKey let jwk = new JsonWebKey() // 2.2.2 Set kty property jwk.kty = 'oct' // 2.2.3 Set k property jwk.k = base64url(key.handle) data = key.handle // 2.2.4 Validate length if (data.length === 16) { jwk.alg = 'A128KW' } else if (data.length === 24) { jwk.alg = 'A192KW' } else if (data.length === 32) { jwk.alg = 'A256KW' } // 2.2.5 Set keyops property jwk.key_ops = key.usages // 2.2.6 Set ext property jwk.ext = key.extractable // 2.2.7 Set result to the result of converting jwk to an ECMAScript object result = jwk } // 2.3 Otherwise... else { throw new KeyFormatNotSupportedError(format) } // 3. Return result return result }
module.exports = function tokenHash(token, signingAlg) { const match = /\w(\d{3})$/.exec(signingAlg); let hashingAlg = 'sha256'; if (match && match[1] !== '256') { hashingAlg = `sha${match[1]}`; } const leftMost = crypto.createHash(hashingAlg).update(token).digest('hex'); return base64url(new Buffer(leftMost.slice(0, leftMost.length / 2), 'hex')); };
Q.all(promises).then(function(results) { var resp = {}; for(var i in results) { resp = extend(resp, results[i].value||{}); } if(resp.access_token && resp.id_token) { var hbuf = crypto.createHmac('sha256', req.session.client_secret).update(resp.access_token).digest(); resp.id_token.ht_hash = base64url(hbuf.toString('ascii', 0, hbuf.length/2)); resp.id_token = jwt.encode(resp.id_token, req.session.client_secret); } deferred.resolve({params: params, type: params.response_type != 'code'?'f':'q', resp: resp}); });
verifyTokenWS: function verifyToken(token) { if (!token) return false; var tokenTab = token.split("."); if (tokenTab.length != 3) return false; var signature = crypto.createHmac("SHA256", config.key).update(tokenTab[0] + "." + tokenTab[1]).digest("bin"); if (base64url(signature) != tokenTab[2]) return false; var payloadDecode = base64url.decode(tokenTab[1]); if (Date.now() > JSON.parse(payloadDecode).exp) return false; return token; },
JWT.prototype.initializeHeader = function (header) { // skip initialization where possible if (!header && this.header) { return; } var keys = this.constructor.headers , schema = this.constructor.registeredHeaders , source = header , target = this.header = {} , operation = JWT.assignValid , options = {} ; // define the instance header and compute base64url JWT.traverse(keys, schema, source, target, operation, options); this.headerB64u = base64url(JSON.stringify(target)); };
exports.checkHashValueRS256 = (content, hashProvided) => { if (!content) return false; // step 1. hash the content var digest = crypto.createHash('sha256').update(content, 'ascii').digest(); // step2. take the first half of the digest, and save it in a buffer var buffer = new Buffer(digest.length/2); for (var i = 0; i < buffer.length; i++) buffer[i] = digest[i]; // step 3. base64url encode the buffer to get the hash var hashComputed = base64url(buffer); return (hashProvided === hashComputed); };
crypto.randomBytes(32, function(err, buffer) { var hash = {}; hash.keyid = keyid; hash.ltiKey = ltiKey; hash.ltiSecret = base64url(buffer); gpg.encrypt( hash.ltiSecret, ['-a', '--always-trust', '--recipient', keyid ], function(err, result, errors) { if (err) { res.status(400).send( 'Could not encrypt secret.' ); } else { hash.encryptedSecret = result; keyAndSecret = new mdb.KeyAndSecret(hash); keyAndSecret.save(function (err) { if (err) res.status(400).send( err ); else res.status(200).send( keyAndSecret.encryptedSecret ); }); } }); });
Object.keys(data).forEach(function(id) { var data_ = data[id]; var center = data_.center; if (center) { data_.viewer_hash = '#' + center[2] + '/' + center[1].toFixed(5) + '/' + center[0].toFixed(5); } data_.is_vector = data_.format == 'pbf'; if (!data_.is_vector) { if (center) { var centerPx = mercator.px([center[0], center[1]], center[2]); data_.thumbnail = center[2] + '/' + Math.floor(centerPx[0] / 256) + '/' + Math.floor(centerPx[1] / 256) + '.' + data_.format; } var query = req.query.key ? ('?key=' + req.query.key) : ''; data_.wmts_link = 'http://wmts.maptiler.com/' + base64url('http://' + req.headers.host + '/data/' + id + '.json' + query) + '/wmts'; } if (data_.filesize) { var suffix = 'kB'; var size = parseInt(data_.filesize, 10) / 1024; if (size > 1024) { suffix = 'MB'; size /= 1024; } if (size > 1024) { suffix = 'GB'; size /= 1024; } data_.formatted_filesize = size.toFixed(2) + ' ' + suffix; } });
crypto.randomBytes(48, function(err, buffer) { var token = base64url(buffer); // BADBAD: Once we disable "always trust" then only people with keys we trust can actually log in; eventually that'll be a reasonable model gpg.encrypt( token, ['--always-trust', '--recipient', keyid ], function(err, result, errors) { if (err) { // The actual error is in err.toString() but revealing // this seems like a bad policy res.status(400).send( 'Could not produce token.' ); } else { // Save token mdb.AccessToken.update( {keyid: keyid}, {keyid: keyid, token: token}, {upsert: true}, function(err) { if (err) { res.status(400).send( 'Could not save token.' ); } else { res.status(200).send( result ); } }); } }); });