process authenticate

@param mixed $signature
@param mixed $extra
@return array
491382
public function processAuthenticate($signature, $extra = null)
    {

        \Facebook\FacebookSession::setDefaultApplication($this->appId, $this->appSecret);

        $session     = new \Facebook\FacebookSession($signature);
        $sessionInfo = $session->getSessionInfo();

        //Make sure that we received a valid token
        if ($sessionInfo->isValid()) {
            return ["SUCCESS"];
        } else {
            return ["FAILURE"];
        }
    }
405077
public function verifySignature($receivedData, Client $client) {

		$signature = isset($receivedData['signature']) ? $receivedData['signature'] : '';
		if (!$signature) {
			return false;
		}

		$responseWithoutSignature = $receivedData;
		unset($responseWithoutSignature["signature"]);

		$baseString = $this->getResponseSignatureBase($responseWithoutSignature);

		$config = $client->getConfig();
		$client->writeToTraceLog('Verifying signature of response of extension ' . $this->extensionId . ', base string is:' . "\n" . $baseString);

		return Crypto::verifySignature($baseString, $signature, $config->bankPublicKeyFile);

	}
488359
public function getUserInformation(array $accessToken, array $extraParameters = [])
    {
        // from http://stackoverflow.com/a/28748285/624544
        list(, $jwt) = explode('.', $accessToken['id_token'], 3);

        // if the token was urlencoded, do some fixes to ensure that it is valid base64 encoded
        $jwt = str_replace(['-', '_'], ['+', '/'], $jwt);

        // complete token if needed
        switch (\strlen($jwt) % 4) {
            case 0:
                break;

            case 2:
            case 3:
                $jwt .= '=';
                break;

            default:
                throw new \InvalidArgumentException('Invalid base64 format sent back');
        }

        $response = parent::getUserInformation($accessToken, $extraParameters);
        $response->setData(base64_decode($jwt));

        return $response;
    }
184451
protected function attemptBasic(Request $request, $field, $extraConditions = [])
    {
        if (! $request->getUser()) {
            return false;
        }

        return $this->attempt(array_merge(
            $this->basicCredentials($request, $field), $extraConditions
        ));
    }
211087
public function process(array $stages, $payload, $extra = [])
    {
        if (!is_array($extra)) {
            $extra = ['source' => $extra];
        }

        return $this->processStages($stages, $payload, $extra);
    }
1150078
public function toBytes(bool $skipSignature = true, bool $skipSecondSignature = true): Buffer
    {
        $buffer = new Writer();
        $buffer->writeUInt8($this->type);
        $buffer->writeUInt32($this->timestamp);
        $buffer->writeHex($this->senderPublicKey);

        $skipRecipientId = $this->type === Types::SECOND_SIGNATURE_REGISTRATION || $this->type === Types::MULTI_SIGNATURE_REGISTRATION;
        if (isset($this->recipientId) && ! $skipRecipientId) {
            $buffer->writeHex(Base58::decodeCheck($this->recipientId)->getHex());
        } else {
            $buffer->fill(21);
        }

        if (isset($this->vendorField) && strlen($this->vendorField) <= 64) {
            $buffer->writeString($this->vendorField);
            $vendorFieldLength = strlen($this->vendorField);

            if ($vendorFieldLength < 64) {
                $buffer->fill(64 - $vendorFieldLength);
            }
        } else {
            $buffer->fill(64);
        }

        $buffer->writeUInt64($this->amount);
        $buffer->writeUInt64($this->fee);

        if (Types::SECOND_SIGNATURE_REGISTRATION === $this->type) {
            $buffer->writeHex($this->asset['signature']['publicKey']);
        }

        if (Types::DELEGATE_REGISTRATION === $this->type) {
            $buffer->writeString($this->asset['delegate']['username']);
        }

        if (Types::VOTE === $this->type) {
            $buffer->writeString(implode('', $this->asset['votes']));
        }

        if (Types::MULTI_SIGNATURE_REGISTRATION === $this->type) {
            $buffer->writeUInt8($this->asset['multisignature']['min']);
            $buffer->writeUInt8($this->asset['multisignature']['lifetime']);
            $buffer->writeString(implode('', $this->asset['multisignature']['keysgroup']));
        }

        if (! $skipSignature && $this->signature) {
            $buffer->writeHex($this->signature);
        }

        if (! $skipSecondSignature && isset($this->signSignature)) {
            $buffer->writeHex($this->signSignature);
        }

        return new Buffer($buffer->toBytes());
    }
1310275
public function verify($key, $signature, $input)
    {
        $signedInput = $this->sign($input, $key);

        return $this->timingSafeEquals($signedInput, $signature);
    }
1081379
public static function authenticateThenDecrypt($secret, $body, $signature) {
    $keys = self::deriveAesKeys($secret);

    $localHmac = hash_hmac('sha256', $body, $keys['auth']);
    if (!self::hash_compare($signature, $localHmac)) {
      throw new InvalidMessageException("Incorrect hash");
    }

    list ($jsonEnvelope, $jsonEncrypted) = explode(Constants::PROTOCOL_DELIM, $body, 2);
    if (strlen($jsonEnvelope) > Constants::MAX_ENVELOPE_BYTES) {
      throw new InvalidMessageException("Oversized envelope");
    }

    $envelope = json_decode($jsonEnvelope, TRUE);
    if (!$envelope) {
      throw new InvalidMessageException("Malformed envelope");
    }

    if (!is_numeric($envelope['ttl']) || Time::getTime() > $envelope['ttl']) {
      throw new InvalidMessageException("Invalid TTL");
    }

    if (!is_string($envelope['iv']) || strlen($envelope['iv']) !== Constants::AES_BYTES * 2 || !preg_match('/^[a-f0-9]+$/', $envelope['iv'])) {
      // AES_BYTES (32) ==> bin2hex ==> 2 hex digits (4-bit) per byte (8-bit)
      throw new InvalidMessageException("Malformed initialization vector");
    }

    $jsonPlaintext = UserError::adapt('Civi\Cxn\Rpc\Exception\InvalidMessageException', function () use ($jsonEncrypted, $envelope, $keys) {
      $cipher = new \Crypt_AES(CRYPT_AES_MODE_CBC);
      $cipher->setKeyLength(Constants::AES_BYTES);
      $cipher->setKey($keys['enc']);
      $cipher->setIV(BinHex::hex2bin($envelope['iv']));
      return $cipher->decrypt($jsonEncrypted);
    });
    return $jsonPlaintext;
  }
1262449
public function verify(JWSInterface $jws, JWKSetInterface $signature_key_set, $detached_payload = null)
    {
        Assertion::inArray($jws->getSignature(0)->getProtectedHeader('alg'), $this->getSupportedSignatureAlgorithms(), sprintf('The signature algorithm "%s" is not supported or not allowed.', $jws->getSignature(0)->getProtectedHeader('alg')));

        $index = null;
        $this->verifier->verifyWithKeySet($jws, $signature_key_set, $detached_payload, $index);
        Assertion::notNull($index, 'JWS signature(s) verification failed.');
        $this->checker_manager->checkJWS($jws, $index);

        return $index;
    }
240738
protected function attemptBasic( Request $request, $field, $extraConditions = [] )
	{
		if ( !$request->getUser() )
			return false;

		$credentials = $this->getBasicCredentials( $request, $field );

		return $this->attempt( array_merge( $credentials, $extraConditions ) );
	}
1099752
public function basic($field = 'email', $extraConditions = [])
    {
        if ($this->check()) {
            return;
        }

        // If a username is set on the HTTP basic request, we will return out without
        // interrupting the request lifecycle. Otherwise, we'll need to generate a
        // request indicating that the given credentials were invalid for login.
        if ($this->attemptBasic($this->getRequest(), $field, $extraConditions)) {
            return;
        }

        return $this->failedBasicResponse();
    }
387435
private static function getSignatures($header, $scheme)
    {
        $signatures = [];
        $items = explode(",", $header);

        foreach ($items as $item) {
            $itemParts = explode("=", $item, 2);
            if ($itemParts[0] == $scheme) {
                array_push($signatures, $itemParts[1]);
            }
        }

        return $signatures;
    }
1350131
protected function verifyExtras(array $extras)
    {
        if (!isset($extras['php-env-builder'])) {
            throw new \InvalidArgumentException(
                'The parameter handler needs to be configured through the ' .
                'extra.php-env-builder setting.'
            );
        }

        if (!is_array($extras['php-env-builder'])) {
            throw new \InvalidArgumentException(
                'The extra.php-env-builder setting must be an array or a configuration object.'
            );
        }

        if (!isset($extras['php-env-builder']['questions']) || !is_array($extras['php-env-builder']['questions'])) {
            throw new \InvalidArgumentException(
                'The extra.php-env-builder.questions setting must be an array of questions.'
            );
        }
    }
610991
public function validAuthenticationResponse($request, $result)
    {
        if (is_bool($result)) {
            return json_encode($result);
        }

        $channelName = $this->normalizeChannelName($request->channel_name);

        return json_encode(['channel_data' => [
            'user_id' => $this->retrieveUser($request, $channelName)->getAuthIdentifier(),
            'user_info' => $result,
        ]]);
    }
269940
public function verify($signature, $identifier, &$initTime, &$expireTime, &$errorMsg)
    {
        try {
            $errorMsg = '';
            $decodedSig = $this->base64Decode($signature);
            $uncompressedSig = gzuncompress($decodedSig);
            if ($uncompressedSig === false) {
                throw new SignatureException('gzuncompress error');
            }
            $json = json_decode($uncompressedSig, true);
            if ($json == false) {
                throw new SignatureException('json_decode error');
            }
            $json = (array)$json;
            if ($json['TLS.identifier'] !== $identifier) {
                throw new SignatureException("identifier error sigid:{$json['TLS.identifier']} id:{$identifier}");
            }
            if ($json['TLS.sdk_appid'] != $this->appId) {
                throw new SignatureException("appid error sigappid:{$json['TLS.appid']} thisappid:{$this->appId}");
            }
            $content = $this->genSignatureContent($json);
            $signature = base64_decode($json['TLS.sig']);
            if ($signature == false) {
                throw new SignatureException('sig json_decode error');
            }
            $succ = $this->verifySignature($content, $signature);
            if (!$succ) {
                throw new SignatureException('verify failed');
            }
            $initTime = $json['TLS.time'];
            $expireTime = $json['TLS.expire_after'];
            return true;
        } catch (SignatureException $ex) {
            $errorMsg = $ex->getMessage();
            return false;
        }
    }
445165
public function extractMeaningAsync($query, $extraParams = [])
    {
        $query = array_merge($extraParams, [
            'lang' => $this->client->getApiLanguage(),
            'query' => $query,
        ]);

        return $this->client->postAsync('query', $query)->then([$this, 'decodeResponse']);
    }
794786
public static function validateSignature($signature, $payload)
    {
        $parts = explode(',', $signature);
        $parameters = [];
        $t = 0;
        // Find the timestamp
        foreach ($parts as $part) {
            parse_str($part, $parsed);
            if (key($parsed) === 't') {
                $t = $parsed['t'];
                break;
            }
        }

        if ($t === 0) {
            return false;
        }

        $wanted = hash_hmac('sha256', $t . '.' . $payload, self::$secret);

        // Find v1 hashes
        foreach ($parts as $part) {
            parse_str($part, $parsed);
            if (key($parsed) === 'v1') {
                if ($wanted === $parsed['v1']) {
                    return true;
                }
            }
        }

        return false;
    }