Calculate response for the challenge-response authentication
177393
def calculate_response(self, challenge, password):
        """"""
        to_hash = (challenge + "-" + password).encode("UTF-16LE")
        hashed = hashlib.md5(to_hash).hexdigest()
        return "{0}-{1}".format(challenge, hashed)
115602
protected function _challengeClient()
    {
        if ($this->_imaProxy) {
            $statusCode = 407;
            $headerName = 'Proxy-Authenticate';
        } else {
            $statusCode = 401;
            $headerName = 'WWW-Authenticate';
        }

        $this->_response->setHttpResponseCode($statusCode);

        // Send a challenge in each acceptable authentication scheme
        if (in_array('basic', $this->_acceptSchemes)) {
            $this->_response->setHeader($headerName, $this->_basicHeader());
        }
        if (in_array('digest', $this->_acceptSchemes)) {
            $this->_response->setHeader($headerName, $this->_digestHeader());
        }
        return new Zend_Auth_Result(
            Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID,
            array(),
            array('Invalid or absent credentials; challenging client')
        );
    }
793977
public function checkAnswer(string $remoteip, string $challenge = null, string $response = null) : Response
    {
        if (empty($remoteip)) {
            throw new Exception('For security reasons, you must pass the remote ip to solvemedia');
        }

        //discard spam submissions
        if (empty($challenge) || empty($response)) {
            return new Response(false, 'incorrect-solution');
        }

        $httpResponse = $this->_client->request(
            'POST',
            self::ADCOPY_VERIFY_SERVER,
            [
                'headers' => ['User-Agent' => 'solvemedia/PHP'],
                'form_params' => [
                    'privatekey' => $this->_privkey,
                    'remoteip' => $remoteip,
                    'challenge' => $challenge,
                    'response' => $response,
                ],
            ]
        );

        if ($httpResponse->getStatusCode() !== 200) {
            return new Response(false, $httpResponse->getReasonPhrase());
        }

        $answers = explode("\n", (string)$httpResponse->getBody());

        if (!empty($this->_hashkey)) {
            // validate message authenticator
            $hash = sha1($answers[0] . $challenge . $this->_hashkey);

            if ($hash !== $answers[2]) {
                return new Response(false, 'hash-fail');
            }
        }

        if (trim($answers[0]) !== 'true') {
            return new Response(false, $answers[1]);
        }

        return new Response(true);
    }
996467
def _get_error_response(self, exc):
        
        if exc.has_code(codes.UNAUTHORIZED):
            return self._get_auth_challenge(exc)
        else:
            if exc.has_code(codes.INTERNAL_SERVER_ERROR):
                logging.getLogger('devil').error('devil caught http error: ' + str(exc), exc_info=True)
            else:
                logging.getLogger('devil').error('devil caught http error: ' + str(exc))
            content = exc.content or ''
            return HttpResponse(content=content, status=exc.get_code_num())
721063
def calc_cred(method, uri, user, passwd, param)
    a_1 = "#{user}:#{param['realm']}:#{passwd}"
    a_2 = "#{method}:#{uri.path}"
    @nonce_count += 1
    message_digest = []
    message_digest << Digest::MD5.hexdigest(a_1)
    message_digest << param['nonce']
    message_digest << ('%08x' % @nonce_count)
    message_digest << param['nonce']
    message_digest << param['qop']
    message_digest << Digest::MD5.hexdigest(a_2)
    header = []
    header << "username=\"#{user}\""
    header << "realm=\"#{param['realm']}\""
    header << "nonce=\"#{param['nonce']}\""
    header << "uri=\"#{uri.path}\""
    header << "cnonce=\"#{param['nonce']}\""
    header << "nc=#{'%08x' % @nonce_count}"
    header << "qop=\"#{param['qop']}\""
    header << "response=\"#{Digest::MD5.hexdigest(message_digest.join(":"))}\""
    header << "algorithm=\"MD5\""
    header << "opaque=\"#{param['opaque']}\"" if param.key?('opaque')
    header.join(", ")
  end
1023886
def get_lm_response(self, flags, challenge):
        
        # If lm compatibility level lower than 3, but the server negotiated NTLM2, generate an
        # NTLM2 response in preference to the weaker LMv1
        if flags & NegotiateFlag.NTLMSSP_NTLM2_KEY and self._lm_compatibility < 3:
            response, key = self._client_challenge + b'\0' * 16, None

        elif 0 <= self._lm_compatibility <= 1:
            response, key = PasswordAuthentication._get_lm_response(self._password, challenge)
        elif self._lm_compatibility == 2:
            response, key = PasswordAuthentication.get_ntlmv1_response(self._password, challenge)
        else:
            response, key = PasswordAuthentication.get_lmv2_response(self._domain, self._username, self._password,
                                                                     challenge, self._client_challenge)
        return response, key
538229
async function challengeCreateFn(authz, challenge, keyAuthorization) {
    /* Do something here */
    log(JSON.stringify(authz));
    log(JSON.stringify(challenge));
    log(keyAuthorization);
}
1242731
def _build_response(self, resp):
        """"""
        # rememberLogin
        # if self.method is 'LOGIN' and resp.json().get('code') == 200:
        #     cookiesJar.save_cookies(resp, NCloudBot.username)
        self.response.content = resp.content
        self.response.status_code = resp.status_code
        self.response.headers = resp.headers
837712
def authenticationAndCipheringResponse(
                                       AuthenticationParameterSRES_presence=0,
                                       MobileId_presence=0):
    """"""
    a = TpPd(pd=0x3)
    b = MessageType(mesType=0x13)  # 00010011
    c = AcReferenceNumberAndSpareHalfOctets()
    packet = a / b / c
    if AuthenticationParameterSRES_presence is 1:
        e = AuthenticationParameterSRES(ieiAPS=0x22)
        packet = packet / e
    if MobileId_presence is 1:
        f = MobileIdHdr(ieiMI=0x23, eightBitMI=0x0)
        packet = packet / f
    return packet
282464
def process_response(self, request, response, spider):
        """"""

        if not self.is_cloudflare_challenge(response):
            return response

        logger = logging.getLogger('cloudflaremiddleware')

        logger.debug(
            'Cloudflare protection detected on %s, trying to bypass...',
            response.url
        )

        cloudflare_tokens, __ = get_tokens(
            request.url,
            user_agent=spider.settings.get('USER_AGENT')
        )

        logger.debug(
            'Successfully bypassed the protection for %s, re-scheduling the request',
            response.url
        )

        request.cookies.update(cloudflare_tokens)
        request.priority = 99999

        return request
241797
async function challengeRemoveFn(authz, challenge, keyAuthorization) {
    /* Do something here */
    log(JSON.stringify(authz));
    log(JSON.stringify(challenge));
    log(keyAuthorization);
}
74634
def _parse_challenge(cls, response):
        
        links = _parse_header_links(response)
        try:
            authzr_uri = links['up']['url']
        except KeyError:
            raise errors.ClientError('"up" link missing')
        return (
            response.json()
            .addCallback(
                lambda body: messages.ChallengeResource(
                    authzr_uri=authzr_uri,
                    body=messages.ChallengeBody.from_json(body)))
            )
396624
def get(req)
    target_uri = req.header.request_uri
    param = Util.hash_find_value(@challenge) { |uri, param|
      Util.uri_part_of(target_uri, uri)
    }
    return nil unless param
    user, passwd = Util.hash_find_value(@auth) { |uri, auth_data|
      Util.uri_part_of(target_uri, uri)
    }
    return nil unless user
    uri = req.header.request_uri
    calc_cred(req.header.request_method, uri, user, passwd, param)
  end
378251
def authenticationAndCipheringRequest(
                                      AuthenticationParameterRAND_presence=0,
                                      CiphKeySeqNr_presence=0):
    """"""
    a = TpPd(pd=0x3)
    b = MessageType(mesType=0x12)  # 00010010
    d = CipheringAlgorithmAndImeisvRequest()
    e = ForceToStandbyAndAcReferenceNumber()
    packet = a / b / d / e
    if AuthenticationParameterRAND_presence is 1:
        g = AuthenticationParameterRAND(ieiAPR=0x21)
        packet = packet / g
    if CiphKeySeqNr_presence is 1:
        h = CiphKeySeqNrHdr(ieiCKSN=0x08, eightBitCKSN=0x0)
        packet = packet / h
    return packet
522506
private boolean isAuthorizationRequired(Response response) {
        if (response != null && response.getStatus() == 401) {
            ResponseImpl responseImpl = (ResponseImpl)response;
            String challengesHeader = responseImpl.getFirstHeader(AUTHENTICATE_HEADER_NAME);

            if (AUTHENTICATE_HEADER_VALUE.equalsIgnoreCase(challengesHeader)) {
                return true;
            }
        }

        return false;
    }
800584
def challenge_auth(username, password, challenge, lower, digest='sha256'):
    
    def hdig(x):
        return fdigest(x).hexdigest()

    fdigest = get_digest(digest)
    luser = lower(username)
    tpass = password[:10].encode("ascii")
    hvalue = hdig("{0}:{1}".format(luser, hdig(tpass)).encode("ascii"))
    bhvalue = hvalue.encode("ascii")
    bchallenge = challenge.encode("ascii")
    return hmac.HMAC(bhvalue, bchallenge, digestmod=fdigest).hexdigest()
616003
def challenge(self):
        
        response = super(ConfigBasicAuth, self).challenge()
        raise with_headers(Unauthorized(), response.headers)