Insert a signature into the outgoing request.

@throws Trustly_SignatureException if private key has not been loaded
yet or if we for some other reason fail to sign the request.

@param Trustly_Data_JSONRPCRequest $request Request to sign.
13159
public function signMerchantRequest($request) {
		if(!isset($this->merchant_privatekey)) {
			throw new Trustly_SignatureException('No private key has been loaded for signing');
		}

		$method = $request->getMethod();
		if($method === NULL) {
			$method = '';
		}
		$uuid = $request->getUUID();
		if($uuid === NULL) {
			$uuid = '';
		}

		$data = $request->getData();

		$serial_data = $method . $uuid . $this->serializeData($data);
		$raw_signature = '';

		$this->clearOpenSSLError();
		if(openssl_sign($serial_data, $raw_signature, $this->merchant_privatekey, OPENSSL_ALGO_SHA1) === TRUE) {
			return base64_encode($raw_signature);
		}

		throw new Trustly_SignatureException('Failed to sign the outgoing merchant request. '. openssl_error_string());
	}
560979
public function sign(string $request) : string
    {
        try {
            return \sodium_crypto_sign_detached(
                $request,
                $this->signatureSecretKey
            );
        } catch (SodiumException $e) {
            throw new InvalidArgumentException($e->getMessage());
        }
    }
846022
public function putAction(Request $request, $key)
    {
        $webspaceKey = $this->getRequestParameter($request, 'webspace', true);
        $this->get('sulu_security.security_checker')->checkPermission(
            new SecurityCondition(SnippetAdmin::getDefaultSnippetsSecurityContext($webspaceKey)),
            PermissionTypes::EDIT
        );

        $default = $request->get('defaultUuid');

        $areas = $this->getLocalizedAreas();
        $area = $areas[$key];

        $defaultSnippet = $this->get('sulu_snippet.default_snippet.manager')->save(
            $webspaceKey,
            $key,
            $default,
            $this->getUser()->getLocale()
        );

        return new JsonResponse(
            [
                'key' => $key,
                'template' => $area['template'],
                'title' => $area['title'],
                'defaultUuid' => $defaultSnippet ? $defaultSnippet->getUuid() : null,
                'defaultTitle' => $defaultSnippet ? $defaultSnippet->getTitle() : null,
                'valid' => true,
            ]
        );
    }
839530
protected function _rsaSha1($request, $credentials)
    {
        if (!function_exists('openssl_pkey_get_private')) {
            throw new RuntimeException('RSA-SHA1 signature method requires the OpenSSL extension.');
        }

        $nonce = isset($credentials['nonce']) ? $credentials['nonce'] : bin2hex(Security::randomBytes(16));
        $timestamp = isset($credentials['timestamp']) ? $credentials['timestamp'] : time();
        $values = [
            'oauth_version' => '1.0',
            'oauth_nonce' => $nonce,
            'oauth_timestamp' => $timestamp,
            'oauth_signature_method' => 'RSA-SHA1',
            'oauth_consumer_key' => $credentials['consumerKey'],
        ];
        if (isset($credentials['consumerSecret'])) {
            $values['oauth_consumer_secret'] = $credentials['consumerSecret'];
        }
        if (isset($credentials['token'])) {
            $values['oauth_token'] = $credentials['token'];
        }
        if (isset($credentials['tokenSecret'])) {
            $values['oauth_token_secret'] = $credentials['tokenSecret'];
        }
        $baseString = $this->baseString($request, $values);

        if (isset($credentials['realm'])) {
            $values['oauth_realm'] = $credentials['realm'];
        }

        if (is_resource($credentials['privateKey'])) {
            $resource = $credentials['privateKey'];
            $privateKey = stream_get_contents($resource);
            rewind($resource);
            $credentials['privateKey'] = $privateKey;
        }

        $credentials += [
            'privateKeyPassphrase' => null,
        ];
        if (is_resource($credentials['privateKeyPassphrase'])) {
            $resource = $credentials['privateKeyPassphrase'];
            $passphrase = stream_get_line($resource, 0, PHP_EOL);
            rewind($resource);
            $credentials['privateKeyPassphrase'] = $passphrase;
        }
        $privateKey = openssl_pkey_get_private($credentials['privateKey'], $credentials['privateKeyPassphrase']);
        $signature = '';
        openssl_sign($baseString, $signature, $privateKey);
        openssl_free_key($privateKey);

        $values['oauth_signature'] = base64_encode($signature);

        return $this->_buildAuth($values);
    }
825053
public function execute($request)
    {
        RequestNotSupportedException::assertSupports($this, $request);

        $model = ArrayObject::ensureArrayObject($request->getModel());
        $request = $model->get('request');
        $signature = $request['signature'];
        unset($request['signature']);

        $mySignature = Signer::sign($request, $this->api['secretKey']);
        if ($mySignature !== $signature) {
            $this->logger->critical('Ecommpay payment signature is invalid');
            throw new BadRequestHttpException();
        }
    }
1266561
public function sign($content, $privateKey)
    {
        try {
            return (new CryptoVirgilSigner($this->hashAlgorithm))->sign($content, $privateKey);
        } catch (Exception $exception) {
            throw new ContentSigningException($exception->getMessage(), $exception->getCode());
        }
    }
473364
@Override
    public void sign(SignableRequest<?> request, AWSCredentials credentials) throws SdkClientException {
        // annonymous credentials, don't sign
        if ( credentials instanceof AnonymousAWSCredentials ) {
            return;
        }

        AWSCredentials sanitizedCredentials = sanitizeCredentials(credentials);

        SigningAlgorithm algorithm = SigningAlgorithm.HmacSHA256;
        String nonce = UUID.randomUUID().toString();

        int timeOffset = request.getTimeOffset();
        Date dateValue = getSignatureDate(timeOffset);
        String date = DateUtils.formatRFC822Date(dateValue);
        boolean isHttps = false;

        if (overriddenDate != null) date = overriddenDate;
        request.addHeader("Date", date);
        request.addHeader("X-Amz-Date", date);

        // AWS3 HTTP requires that we sign the Host header
        // so we have to have it in the request by the time we sign.
        String hostHeader = request.getEndpoint().getHost();
        if (SdkHttpUtils.isUsingNonDefaultPort(request.getEndpoint())) {
            hostHeader += ":" + request.getEndpoint().getPort();
        }
        request.addHeader("Host", hostHeader);

        if ( sanitizedCredentials instanceof AWSSessionCredentials ) {
            addSessionCredentials(request, (AWSSessionCredentials) sanitizedCredentials);
        }
        byte[] bytesToSign;
        String stringToSign;
        if (isHttps) {
            request.addHeader(NONCE_HEADER, nonce);
            stringToSign = date + nonce;
            bytesToSign = stringToSign.getBytes(UTF8);
        } else {
            String path = SdkHttpUtils.appendUri(request.getEndpoint().getPath(), request.getResourcePath());

            /*
             * AWS3 requires all query params to be listed on the third line of
             * the string to sign, even if those query params will be sent in
             * the request body and not as a query string. POST formatted query
             * params should *NOT* be included in the request payload.
             */
            stringToSign = request.getHttpMethod().toString() + "\n"
                    + getCanonicalizedResourcePath(path) + "\n"
                    + getCanonicalizedQueryString(request.getParameters()) + "\n"
                    + getCanonicalizedHeadersForStringToSign(request) + "\n"
                    + getRequestPayloadWithoutQueryParams(request);
            bytesToSign = hash(stringToSign);
        }
        if (log.isDebugEnabled())
            log.debug("Calculated StringToSign: " + stringToSign);

        String signature = signAndBase64Encode(bytesToSign,
                sanitizedCredentials.getAWSSecretKey(), algorithm);

        StringBuilder builder = new StringBuilder();
        builder.append(isHttps ? HTTPS_SCHEME : HTTP_SCHEME).append(" ");
        builder.append("AWSAccessKeyId=" + sanitizedCredentials.getAWSAccessKeyId() + ",");
        builder.append("Algorithm=" + algorithm.toString() + ",");

        if (!isHttps) {
            builder.append(getSignedHeadersComponent(request) + ",");
        }

        builder.append("Signature=" + signature);
        request.addHeader(AUTHORIZATION_HEADER, builder.toString());
    }
832971
public function auth($request)
    {
        if (Str::startsWith($request->channel_name, ['private-', 'presence-']) &&
            ! $request->user()) {
            throw new HttpException(403);
        }

        return parent::verifyUserCanAccessChannel(
            $request, str_replace(['private-', 'presence-'], '', $request->channel_name)
        );
    }
523474
protected function getSignatureFromRequest(Request $request): string
    {
        if (!$request->hasHeader(self::HEADER_AUTHENTICATE_SIGNATURE)) {
            throw new UnauthorizedException('Signature is required.');
        }

        $signature = current($request->getHeader(self::HEADER_AUTHENTICATE_SIGNATURE));

        return $signature;
    }
311978
public function signRequest(
        RequestInterface $request,
        CredentialsInterface $credentials
    ) {
        if (!$request->hasHeader('x-amz-content-sha256')) {
            $request = $request->withHeader(
                'X-Amz-Content-Sha256',
                $this->getPayload($request)
            );
        }

        return parent::signRequest($request, $credentials);
    }
102832
public function checkForToken(Request $request)
    {
        if (! $this->auth->parser()->setRequest($request)->hasToken()) {
            throw new UnauthorizedHttpException('jwTauth', 'Token not provided');
        }
    }
325309
public function signTokenRequest(TokenRequest $tokenRequest, $privateKey)
    {
        openssl_sign($tokenRequest->getIssuer() . ':' . $tokenRequest->getUsername(), $signature, $privateKey);

        return $tokenRequest->setSignature(base64_encode($signature));
    }
1108285
private function sanitizeRequestOrThrowExceptionIfInvalid($request)
    {
        $isObject = ($request instanceof \stdClass);
        if (!is_array($request) && !$isObject) {
            throw new InvalidRequestException(
                'Request builder is intended to be used with arrays or instances of \\stdClass'
            );
        }
        return $isObject ? json_decode(json_encode($request), true) : $request;
    }
44317
protected function getSignatureMethod(&$request)
    {
        $signature_method =
            @$request->getParameter("oauth_signature_method");
        
        if (!$signature_method) {
            // According to chapter 7 ("Accessing Protected Ressources") the signature-method
            // parameter is required, and we can't just fallback to PLAINTEXT
            throw new OAuthException('No signature method parameter. This parameter is required');
        }
        
        if (!in_array($signature_method,
            array_keys($this->signature_methods))
        ) {
            throw new OAuthException(
                "Signature method '$signature_method' not supported " .
                "try one of the following: " .
                implode(", ", array_keys($this->signature_methods))
            );
        }
        
        return $this->signature_methods[ $signature_method ];
    }
88396
protected function _sign($parameters)
    {
        // Fixup our private key, copy-pasting the key might lead to whitespace faults
        if (!preg_match('/-----BEGIN (RSA )?PRIVATE KEY-----(.*)-----END (RSA )?PRIVATE KEY-----/si', $this->client->getPrivateKey(), $matches)) {
            die('<p>Could not find your private key, please supply your private key in the ApiSettings file. You can request a new private key in your TransIP Controlpanel.</p>');
        }

        $key = $matches[2];
        $key = preg_replace('/\s*/s', '', $key);
        $key = chunk_split($key, 64, "\n");

        $key = "-----BEGIN PRIVATE KEY-----\n" . $key . "-----END PRIVATE KEY-----";

        $digest = $this->_sha512Asn1($this->_encodeParameters($parameters));
        if (!@openssl_private_encrypt($digest, $signature, $key)) {
            die('<p>Could not sign your request, please supply your private key in the ApiSettings file. You can request a new private key in your TransIP Controlpanel.</p>');
        }

        return base64_encode($signature);
    }
1221858
public function insertCredentials($request) {
		$request->setParam('Username', $this->api_username);
		if(isset($this->session_uuid)) {
			$request->setParam('Password', $this->session_uuid);
		} else {
			$request->setParam('Password', $this->api_password);
		}
		return TRUE;
	}
616256
private function checkSignature($request)
	{
		$serverToken = $this->_config['serverToken'];
		$sigature = $this->getSign($serverToken,$request['nonce'],$request['timestamp']);
		if($sigature == $request['signature'])
			return true;
		return false;
	}