How to use the base64url.encode function in base64url

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 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;
        });
      });
github mozilla / addons-frontend / tests / unit / helpers.js View on Github external
export function userAuthToken(
  dataOverrides = {},
  { tokenCreatedAt = (Date.now() / 1000).toFixed(0), tokenData } = {},
) {
  const data = {
    user_id: 102345,
    ...dataOverrides,
  };

  let encodedToken = tokenData;
  if (!encodedToken) {
    encodedToken = base64url.encode(JSON.stringify(data));
  }

  const base62 = getDjangoBase62();
  const timestamp = base62.encode(tokenCreatedAt);
  const sig = base64url.encode('pretend-this-is-a-signature');

  return `${encodedToken}:${timestamp}:${sig}`;
}
github decentralized-identity / sidetree / lib / core / versions / latest / Encoder.ts View on Github external
public static encode (content: Buffer | string): string {
    const encodedContent = base64url.encode(content);
    return encodedContent;
  }
github oauthinaction / oauth-in-action-code / exercises / ch-11-ex-3 / authorizationServer.js View on Github external
* Create a signed JWT using RS256 instead of this unsigned one
				 */
				
				var header = { 'typ': 'JWT', 'alg': 'none' };
				var payload = {
					iss: 'http://localhost:9001/',
					sub: code.user ? code.user.sub : undefined,
					aud: 'http://localhost:9002/',
					iat: Math.floor(Date.now() / 1000),
					exp: Math.floor(Date.now() / 1000) + (5 * 60),
					jti: randomstring.generate(8)
				};
				
				var access_token = base64url.encode(JSON.stringify(header))
					+ '.'
					+ base64url.encode(JSON.stringify(payload))
					+ '.';

				nosql.insert({ access_token: access_token, client_id: clientId, scope: code.scope, user: code.user });

				console.log('Issuing access token %s', access_token);

				var token_response = { access_token: access_token, token_type: 'Bearer',  scope: code.scope.join(' ') };

				res.status(200).json(token_response);
				console.log('Issued tokens for code %s', req.body.code);
				
				return;
			} else {
				console.log('Client mismatch, expected %s got %s', code.request.client_id, clientId);
				res.status(400).json({error: 'invalid_grant'});
				return;
github microsoft / perfview / src / PerfViewJS / spa / src / components / Callers.tsx View on Github external
static constructAPICacheKeyFromRouteKey(r: string) {
        var routeKey = JSON.parse(base64url.decode(r, "utf8"));
        return 'filename=' + routeKey.a + '&stackType=' + routeKey.b + '&pid=' + routeKey.c + '&start=' + base64url.encode(routeKey.d, "utf8") + '&end=' + base64url.encode(routeKey.e, "utf8") + '&groupPats=' + base64url.encode(routeKey.f, "utf8") + '&foldPats=' + base64url.encode(routeKey.g, "utf8") + '&incPats=' + base64url.encode(routeKey.h, "utf8") + '&excPats=' + base64url.encode(routeKey.i, "utf8") + '&foldPct=' + routeKey.j + '&drillIntoKey=' + routeKey.k;
    }
github PeculiarVentures / node-webcrypto-p11 / built / algs / aes.js View on Github external
Aes.exportKey = function (session, format, key, callback) {
        try {
            var vals = key.key.getAttribute({ value: null, valueLen: null });
            switch (format.toLowerCase()) {
                case "jwk":
                    var aes = /AES-(\w+)/.exec(key.algorithm.name)[1];
                    var jwk = {
                        kty: "oct",
                        k: base64url.encode(vals.value),
                        alg: "A" + vals.valueLen * 8 + aes,
                        ext: true
                    };
                    callback(null, jwk);
                    break;
                case "raw":
                    callback(null, vals.value);
            }
        }
        catch (e) {
            callback(e, null);
        }
    };
    Aes.importKey = function (session, format, keyData, algorithm, extractable, keyUsages, callback) {
github fido-alliance / webauthn-demo / utils.js View on Github external
throw new Error('User was NOT presented durring authentication!');

        let clientDataHash  = hash(base64url.toBuffer(webAuthnResponse.response.clientDataJSON))
        let reservedByte    = Buffer.from([0x00]);
        let publicKey       = COSEECDHAtoPKCS(authrDataStruct.COSEPublicKey)
        let signatureBase   = Buffer.concat([reservedByte, authrDataStruct.rpIdHash, clientDataHash, authrDataStruct.credID, publicKey]);

        let PEMCertificate = ASN1toPEM(ctapMakeCredResp.attStmt.x5c[0]);
        let signature      = ctapMakeCredResp.attStmt.sig;

        response.verified = verifySignature(signature, signatureBase, PEMCertificate)

        if(response.verified) {
            response.authrInfo = {
                fmt: 'fido-u2f',
                publicKey: base64url.encode(publicKey),
                counter: authrDataStruct.counter,
                credID: base64url.encode(authrDataStruct.credID)
            }
        }
    }

    return response
}
github decentralized-identity / github-did / packages / app / src / components / DIDWallet / DisplayWallet.js View on Github external
const hashEncrypted = (data) => {
  const encodedPayload = base64url.encode(Buffer.from(data));
  return base64url.encode(
    crypto
      .createHash('sha256')
      .update(base64url.toBuffer(encodedPayload))
      .digest(),
  );
};

base64url

For encoding to/from base64urls

MIT
Latest version published 6 years ago

Package Health Score

74 / 100
Full package analysis