Unpack a JSON-serialized JWT or a compact-serialized JWT
    Returns (header, payload, signature, signing_input) on success
    Raises DecodeError on bad input
429244
def unpack_token(token):
    
    if isinstance(token, (unicode,str)):
        return _decode_token_compact(token)

    else:
        return _decode_token_json(token)
710597
def encode(self, payload):
        
        token = jwt.encode(payload, self.signing_key, algorithm=self.algorithm)
        return token.decode('utf-8')
646409
def decode(stream, strict=True):
    
    if not isinstance(stream, util.BufferedByteStream):
        stream = util.BufferedByteStream(stream)

    # read the version
    version = stream.read(2)

    if version != HEADER_VERSION:
        raise pyamf.DecodeError('Unknown SOL version in header')

    # read the length
    length = stream.read_ulong()

    if strict and stream.remaining() != length:
        raise pyamf.DecodeError('Inconsistent stream header length')

    # read the signature
    signature = stream.read(10)

    if signature != HEADER_SIGNATURE:
        raise pyamf.DecodeError('Invalid signature')

    length = stream.read_ushort()
    root_name = stream.read_utf8_string(length)

    # read padding
    if stream.read(3) != PADDING_BYTE * 3:
        raise pyamf.DecodeError('Invalid padding read')

    decoder = pyamf.get_decoder(stream.read_uchar())
    decoder.stream = stream

    values = {}

    while 1:
        if stream.at_eof():
            break

        name = decoder.readString()
        value = decoder.readElement()

        # read the padding
        if stream.read(1) != PADDING_BYTE:
            raise pyamf.DecodeError('Missing padding byte')

        values[name] = value

    return (root_name, values)
853132
def sign(self, payload):
        
        if self.authenticator:
            return self.authenticator.signed(payload)
        return payload
929092
def _data_to_sign(self) -> bytes:
        
        packed = self.packed()

        field = type(packed).fields_spec[-1]
        assert field.name == 'signature', 'signature is not the last field'

        # this slice must be from the end of the buffer
        return packed.data[:-field.size_bytes]
51587
def get_unverified_header(self, jwt):
        
        headers = self._load(jwt)[2]
        self._validate_headers(headers)

        return headers
1321517
def unpack(cls, msg, client, server, request_id):
        
        payload_document = OrderedDict()
        flags, = _UNPACK_UINT(msg[:4])
        pos = 4
        if flags != 0 and flags != 2:
            raise ValueError('OP_MSG flag must be 0 or 2 not %r' % (flags,))

        while pos < len(msg):
            payload_type, = _UNPACK_BYTE(msg[pos:pos + 1])
            pos += 1
            payload_size, = _UNPACK_INT(msg[pos:pos + 4])
            if payload_type == 0:
                doc = bson.decode_all(msg[pos:pos + payload_size],
                                      CODEC_OPTIONS)[0]
                payload_document.update(doc)
                pos += payload_size
            elif payload_type == 1:
                section_size, = _UNPACK_INT(msg[pos:pos + 4])
                pos += 4
                identifier, pos = _get_c_string(msg, pos)
                # Section starts w/ 4-byte size prefix, identifier ends w/ nil.
                documents_len = section_size - len(identifier) - 1 - 4
                documents = bson.decode_all(msg[pos:pos + documents_len],
                                            CODEC_OPTIONS)
                payload_document[identifier] = documents
                pos += documents_len

        database = payload_document['$db']
        return OpMsg(payload_document, namespace=database, flags=flags,
                     _client=client, request_id=request_id,
                     _server=server)
1277621
function decodeToken (tokenStr) {
  if (!tokenStr || tokenStr === '') return null
  try {
    return jwtDecode(tokenStr)
  } catch (error) {
    logger.error({
      description: 'Error decoding token.',
      error, func: 'decodeToken', file: 'token'
    })
    return null
  }
}
383261
def _is_compact_jws(self, jws):
        
        try:
            jwt = JWSig().unpack(jws)
        except Exception as err:
            logger.warning('Could not parse JWS: {}'.format(err))
            return False

        if "alg" not in jwt.headers:
            return False

        if jwt.headers["alg"] is None:
            jwt.headers["alg"] = "none"

        if jwt.headers["alg"] not in SIGNER_ALGS:
            logger.debug("UnknownSignerAlg: %s" % jwt.headers["alg"])
            return False

        self.jwt = jwt
        return True
532182
async function _verifyToken (jwksClient, token) {
  const decoded = jwt.decode(token, { complete: true })
  const signingKey = await jwksClient.getSigningKeyAsync(decoded.header.kid)
  return jwt.verifyAsync(token, signingKey.publicKey || signingKey.rsaPublicKey)
}
416074
def get_decoded_jwt(request):
    
    jwt_cookie = request.COOKIES.get(jwt_cookie_name(), None)

    if not jwt_cookie:
        return None
    return jwt_decode_handler(jwt_cookie)
682783
def get_token_payload(token)

        # Attempt to decode without verifying. May raise DecodeError.
        decoded = JWT.decode token, nil, false
        payload = decoded[0]

        # At this point, we know that the token is not expired and
        # well formatted. Find out if the payload is well defined.
        if payload.nil?
          # :nocov:
          logger.error("Token payload is nil: #{token}")
          raise UNAUTHORIZED_ERROR, "Invalid token"
          # :nocov:
        end

        return payload

      rescue JWT::DecodeError => e
        logger.error("Token decode error: #{e.message}")
        raise UNAUTHORIZED_ERROR, "Invalid token"
      end
1234233
def decrypt(self, token, key, cek=None):
        
        if not isinstance(token, JWEnc):
            jwe = JWEnc().unpack(token)
        else:
            jwe = token

        self.jwt = jwe.encrypted_key()
        jek = jwe.encrypted_key()

        _decrypt = RSAEncrypter(self.with_digest).decrypt

        _alg = jwe.headers["alg"]
        if cek:
            pass
        elif _alg == "RSA-OAEP":
            cek = _decrypt(jek, key, 'pkcs1_oaep_padding')
        elif _alg == "RSA-OAEP-256":
            cek = _decrypt(jek, key, 'pkcs1_oaep_256_padding')
        elif _alg == "RSA1_5":
            cek = _decrypt(jek, key)
        else:
            raise NotSupportedAlgorithm(_alg)

        self["cek"] = cek
        enc = jwe.headers["enc"]
        if enc not in SUPPORTED["enc"]:
            raise NotSupportedAlgorithm(enc)

        auth_data = jwe.b64_protected_header()

        msg = self._decrypt(enc, cek, jwe.ciphertext(),
                            auth_data=auth_data,
                            iv=jwe.initialization_vector(),
                            tag=jwe.authentication_tag())

        if "zip" in jwe.headers and jwe.headers["zip"] == "DEF":
            msg = zlib.decompress(msg)

        return msg
797949
def unpack(cls, msg, client, server, request_id):
        
        flags, = _UNPACK_INT(msg[:4])
        namespace, pos = _get_c_string(msg, 4)
        docs = bson.decode_all(msg[pos:], CODEC_OPTIONS)
        return cls(*docs, namespace=namespace, flags=flags, _client=client,
                   request_id=request_id, _server=server)
1203038
def validate_and_decode(jwt_bu64, cert_obj):
    
    public_key = cert_obj.public_key()
    message = '.'.join(d1_common.cert.jwt.get_bu64_tup(jwt_bu64)[:2])
    signature = d1_common.cert.jwt.get_jwt_tup(jwt_bu64)[2]
    try:
        public_key.verify(
            signature,
            message,
            cryptography.hazmat.primitives.asymmetric.padding.PKCS1v15(),
            cryptography.hazmat.primitives.hashes.SHA256(),
        )
    except cryptography.exceptions.InvalidSignature as e:
        raise Exception('Signature is invalid. error="{}"'.format(str(e)))
    return d1_common.cert.jwt.get_jwt_dict(jwt_bu64)
1323592
def decode_message(message)
      begin
        msg = MessagePack.unpack(message, symbolize_keys: true)
      rescue => ex
        raise InvalidMessageError, "couldn't unpack message: #{ex}"
      end
      begin
        klass = Utils.full_const_get msg[:type]
        o = klass.new(*msg[:args])
        o.id = msg[:id] if o.respond_to?(:id=) && msg[:id]
        o
      rescue => ex
        raise InvalidMessageError, "invalid message: #{ex}"
      end
    end
774765
def _decode_header(auth_header, client_id, client_secret):
    
    try:
        token = auth_header.split()[1]
        payload = jwt.decode(
            token,
            client_secret,
            audience=client_id)
    except jwt.ExpiredSignature:
        raise exceptions.NotAuthorizedException(
            'Token has expired, please log in again.')
    # is valid client
    except jwt.InvalidAudienceError:
        message = 'Incorrect audience, expected: {}'.format(
            client_id)
        raise exceptions.NotAuthorizedException(message)
    # is valid token
    except jwt.DecodeError:
        raise exceptions.NotAuthorizedException(
            'Token signature could not be validated.')
    except Exception as e:
        raise exceptions.NotAuthorizedException(
            'Token signature was malformed. {}'.format(e.message))
    return token, payload