How to use base64url - 10 common examples

To help you get started, we’ve selected a few base64url examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github interledger-deprecated / ilp-plugin-chain / src / plugin.js View on Github external
if (transfer.executionCondition === MESSAGE_STRING) {
          this._handleLedgerMessage(transfer)
          break
        }

        // check that the incoming transfer is locked with the right control program
        await escrow.verify({
          utxo: output,
          client: this._client,
          sourceReceiver: output.referenceData.sourceReceiver,
          destinationPubkey: this._key.pubkey,
          amount: output.amount,
          assetId: output.assetId,
          // TODO decide on which part of the codebase is dealing with which date format
          expiresAt: moment(output.referenceData.expiresAt).valueOf(),
          condition: base64url.decode(output.referenceData.executionCondition, 'hex')
        })
        // TODO check that all the referenceData we expect is there
        debug('emitting incoming_prepare', transfer)
        try {
          this._safeEmit('incoming_prepare', transfer)
        } catch (err) {
          console.error('error in event handler', err)
        }
      } else if (this._outputIsFromUs(output)) {
        const transfer = this._parseTransferFromOutput(output)
        this._safeEmit('outgoing_prepare', transfer)
      }
    }
  }
github oauthinaction / oauth-in-action-code / exercises / ch-11-ex-4 / client.js View on Github external
console.log('Got access token: %s', access_token);
		if (body.refresh_token) {
			refresh_token = body.refresh_token;
			console.log('Got refresh token: %s', refresh_token);
		}
		
		if (body.id_token) {
			console.log('Got ID token: %s', body.id_token);
			
			// check the id token
			var pubKey = jose.KEYUTIL.getKey(rsaKey);
			var signatureValid = jose.jws.JWS.verify(body.id_token, pubKey, ['RS256']);
			if (signatureValid) {
				console.log('Signature validated.');
				var tokenParts = body.id_token.split('.');
				var payload = JSON.parse(base64url.decode(tokenParts[1]));
				console.log('Payload', payload);
				if (payload.iss == 'http://localhost:9001/') {
					console.log('issuer OK');
					if ((Array.isArray(payload.aud) && _.contains(payload.aud, client.client_id)) || 
						payload.aud == client.client_id) {
						console.log('Audience OK');
				
						var now = Math.floor(Date.now() / 1000);
				
						if (payload.iat <= now) {
							console.log('issued-at OK');
							if (payload.exp >= now) {
								console.log('expiration OK');
						
								console.log('Token valid!');
github blockstack / jsontokens-js / src / decode.ts View on Github external
export function decodeToken(token: string | TokenInterface): TokenInterface {
    if (typeof token === 'string') {
        // decompose the token into parts
        const tokenParts = token.split('.')
        const header = JSON.parse(base64url.decode(tokenParts[0]))
        const payload = JSON.parse(base64url.decode(tokenParts[1]))
        const signature = tokenParts[2]

        // return the token object
        return {
            header: header,
            payload: payload,
            signature: signature
        }
    } else if (typeof token === 'object') {
        if (typeof token.payload !== 'string') {
            throw new Error('Expected token payload to be a base64 or json string')
        }
        let payload = token.payload
        if (token.payload[0] !== '{') {
            payload = base64url.decode(payload)
github AzureAD / passport-azure-ad / lib / jwe.js View on Github external
/****************************************************************************
   *   JWE compact format structure
   ****************************************************************************
   * BASE64URL(UTF8(JWE Protected Header)) || '.' ||
   * BASE64URL(JWE Encrypted Key) || '.' || 
   * BASE64URL(JWE Initialization Vector) || '.' || 
   * BASE64URL(JWE Ciphertext) || '.' || 
   * BASE64URL(JWE Authentication Tag)
   ***************************************************************************/
  var parts = jweString.split('.');
  if (parts.length !== 5)
    return callback(new Error('In jwe.decrypt: invalid JWE string, it has ' + parts.length + ' parts instead of 5'), null);
  
  var header;
  try {
    header = JSON.parse(base64url.decode(parts[0], 'binary'));
  } catch (ex) {
    return callback(new Error('In jwe.decrypt: failed to parse JWE header'), null);
  }

  var aad = createBuffer(parts[0]);
  var encrypted_cek = base64url.toBuffer(parts[1]);
  var iv = base64url.toBuffer(parts[2]);
  var cipherText = base64url.toBuffer(parts[3]);
  var authTag = base64url.toBuffer(parts[4]);

  log.info('In jwe.decrypt: the header is ' + JSON.stringify(header));

  var cek_result;
  var content_result;

  // special treatment of 'dir'
github anvilresearch / jose / src / jose / JWT.js View on Github external
let ExtendedJWT = this
    let protectedHeader, payload, signature

    // Parse
    if (typeof data === 'string') {
      let segments = data.split('.')

      if (![3, 5].includes(segments.length)) {
        throw new DataError('Malformed JWT')
      }

      // Decode base64url
      if (segments.length === 3) {
        try {
          protectedHeader = JSON.parse(base64url.decode(segments[0]))
          payload = JSON.parse(base64url.decode(segments[1]))
          signature = segments[2]
        } catch (err) {
          throw new DataError('Malformed JWS')
        }
      }

      if (segments.length === 5) {
        // TODO JWE
      }
    }

    // Sanity Check
    if (typeof protectedHeader !== 'object' || protectedHeader === null || Array.isArray(protectedHeader)) {
      throw new DataError('JWT Header must be an object')
    }
github AzureAD / passport-azure-ad / lib / jwe.js View on Github external
***************************************************************************/
  var parts = jweString.split('.');
  if (parts.length !== 5)
    return callback(new Error('In jwe.decrypt: invalid JWE string, it has ' + parts.length + ' parts instead of 5'), null);
  
  var header;
  try {
    header = JSON.parse(base64url.decode(parts[0], 'binary'));
  } catch (ex) {
    return callback(new Error('In jwe.decrypt: failed to parse JWE header'), null);
  }

  var aad = createBuffer(parts[0]);
  var encrypted_cek = base64url.toBuffer(parts[1]);
  var iv = base64url.toBuffer(parts[2]);
  var cipherText = base64url.toBuffer(parts[3]);
  var authTag = base64url.toBuffer(parts[4]);

  log.info('In jwe.decrypt: the header is ' + JSON.stringify(header));

  var cek_result;
  var content_result;

  // special treatment of 'dir'
  if (header.alg === 'dir') {
    content_result = decryptContentForDir(header, jweKeyStore, cipherText, iv, authTag, aad, log);
  } else {
    /****************************************************************************
     *  cek decryption
     ***************************************************************************/
    var cek_result = decryptCEK(header, encrypted_cek, jweKeyStore, log);
    if (cek_result.error)
github fabric8io / openshift-auth-proxy / lib / config.js View on Github external
// read in all the files with secrets, keys, certs
//
var files = {};
switch (config['auth-mode']) {
  case 'oauth2':
    // look for an oauth secret -- crash if not there
    files.oauthSecret = fs.readFileSync(config['oauth-secret'], 'utf8').
	                   replace(/(\n|\r)/gm,''); // newlines can mismatch secret
    try { // ok if missing, we will generate
      files.sessionSecret = fs.readFileSync(config['session-secret'], 'utf8');
    } catch(err) {
      console.error('error reading session secret: %s', JSON.stringify(err));
    } finally { // just ignore if the file is not there
      if (files.sessionSecret == null) {
        console.error('generating session secret (will not work with scaled service)');
        files.sessionSecret = require('base64url')(require('crypto').randomBytes(256)).substring(0, 256);
      }
    };
    // don't break, do both.
  case 'bearer': // and oauth2 as well:
    // ensure we validate connections to master w/ master CA.
    // technically this might not be required, but passport fails
    // silently if it *is* needed and is not present.
    var cas = https.globalAgent.options.ca || [];
    cas.push(fs.readFileSync(config['master-ca'], 'utf8'));
    https.globalAgent.options.ca = cas;
    break;
  case 'mutual_tls':
    try {
      files.mutualTlsCa = fs.readFileSync(config['mutual-tls-ca'], 'utf8');
    } catch(err) {
        throw 'No CA read for mutual TLS. Looked in: ' + config['mutual-tls-ca'];
github decentralized-identity / element / packages / element-lib / src / func / batchFileToOperations.js View on Github external
const batchFileToOperations = batchFile => batchFile.operations.map((op) => {
  const decoded = base64url.decode(op);
  const decodedOperation = JSON.parse(decoded);
  // this was wrong!!!! THE OPERATION HASH IS THE HASH OF THE PAYLOAD
  // TODO: use this typescript package instead...
  // https://github.com/decentralized-identity/sidetree/blob/361d86b5f10eb8174f4fb5f8871a31384da3e569/lib/core/Operation.ts#L184
  const operationHash = base64url.encode(
    crypto
      .createHash('sha256')
      .update(base64url.toBuffer(decodedOperation.payload))
      .digest(),
  );
  return {
    operationHash,
    decodedOperation,
    decodedOperationPayload: JSON.parse(base64url.decode(decodedOperation.payload)),
  };
});
github ibm-cloud-security / appid-serversdk-nodejs / samples / cloud-directory-app-sample-server.js View on Github external
selfServiceManager.getForgotPasswordConfirmationResult(context).then(function (result) {
		let uuid = result && result.uuid;
		if (result && result.success) {
			//generate one time code and pass it to the reset password form,
			// here we do that in memory but it better to use DB like Redis to do that and store it for temporary time.
			let oneTimeCode = base64url.encode(crypto.randomBytes(24));
			resetPasswordCodesMap.set(oneTimeCode, {uuid: uuid ,tenantId: tenantId});
			logger.debug('rendering ' + resetPasswordFormEjs);
			_render(req, res, resetPasswordFormEjs, {uuid: uuid, code: oneTimeCode}, language);
		} else {
			if (result.error.code === 'NOT_FOUND') {
				logger.debug('forgot password result - failure: ' + result.error.description);
				_render(req, res, resetPasswordExpiredEjs, {uuid: uuid, errorStatusCode: 'NOT_FOUND', errorDescription: result.error.description}, language);
			} else {
				logger.error('unexpected forgot password result ' + result);
				res.status(500);
				res.send('Something went wrong');
			}
		}
	}).catch(function (err) {
		logger.error(err);
github manifoldco / torus-cli / cli / lib / user / crypto.js View on Github external
}).then(function (buf) {
          // Base64 the master value for transmission
          data.master.value = base64url.encode(buf);
          return data;
        });
      });

base64url

For encoding to/from base64urls

MIT
Latest version published 6 years ago

Package Health Score

74 / 100
Full package analysis