See: https://mobius.network/docs/#transfer-unmanaged

@param      $toAddress
@param      $numTokens
@param      $privateKey
@param null $tokenAddress
@param null $gasPrice
@param null $gasLimit
@return string The transaction hash
@throws \ErrorException
338950
public function transferUnmanaged($toAddress, $numTokens, $privateKey, $tokenAddress = null, $gasPrice = null, $gasLimit = null)
    {
        $parameters = [
            'address_to' => $toAddress,
            'num_tokens' => $numTokens,
            'private_key' => $privateKey,
        ];

        // If $tokenAddress is set, use that instead of the internal tokenUid
        if ($tokenAddress !== null) {
            $parameters['token_address'] = $tokenAddress;
        }
        else {
            $parameters['token_uid'] = $this->tokenUid;
        }

        // Only include gasPrice and gasLimit if they're set
        if ($gasPrice !== null) $parameters['gas_price'] = $gasPrice;
        if ($gasLimit !== null) $parameters['gas_limit'] = $gasLimit;

        $response = $this->apiClient->post('tokens/transfer/unmanaged',
            $parameters
        );

        if (!isset($response['tx_hash'])) throw new \ErrorException('Unexpected API response: ' . print_r($response, true));

        return $response['tx_hash'];
    }
335753
public function decode($token, $key = null)
    {
        $key = empty($key) ? $this->key : $key;

        $timestamp = empty($this->timestamp) ? time() : $this->timestamp;

        $segments = explode('.', $token);
        $segments = array_map('trim', $segments);

        if (count($segments) == 3) {
            list($headers, $payload, $signature) = $segments;

            // Base64 decode headers
            if (false === ($headers = Base64::decode($headers))) {
                $this->errors[] = 'Invalid header base64 decoding';

                return false;
            }

            // Json decode headers
            if (null === ($headers = Json::decode($headers))) {
                $this->errors[] = 'Invalid header json decoding';

                return false;
            }

            // Validate algorithm header
            if (empty($headers->alg)) {
                $this->errors[] = 'Invalid algorithm';

                return false;
            } elseif ( ! Algorithm::validate($headers->alg)) {
                $this->errors[] = 'Unsupported algorithm';

                return false;
            }

            // Base64 decode payload
            if (false === ($payload = Base64::decode($payload))) {
                $this->errors[] = 'Invalid payload base64 decoding';

                return false;
            }

            // Json decode payload
            if (null === ($payload = Json::decode($payload))) {
                $this->errors[] = 'Invalid payload json decoding';

                return false;
            }

            // Base64 decode payload
            if (false === ($signature = Base64::decode($signature))) {
                $this->errors[] = 'Invalid signature base64 decoding';

                return false;
            }

            if (Signature::verify($token, $signature, $key, $headers->alg) === false) {
                $this->errors[] = 'Invalid signature';

                return false;
            }

            // Check if the nbf if it is defined. This is the time that the
            // token can actually be used. If it's not yet that time, abort.
            if (isset($payload->nbf) && $payload->nbf > $timestamp) {
                $this->errors[] = 'Cannot handle token prior to ' . date(\DateTime::ISO8601, $payload->nbf);

                return false;
            }

            // Check that this token has been created before 'now'. This prevents
            // using tokens that have been created for later use (and haven't
            // correctly used the nbf claim).
            if (isset($payload->iat) && $payload->iat > $timestamp) {
                $this->errors[] = 'Cannot handle token prior to ' . date(\DateTime::ISO8601, $payload->iat);

                return false;
            }
            // Check if this token has expired.
            if (isset($payload->exp) && $timestamp >= $payload->exp) {
                $this->errors[] = 'Expired token';

                return false;
            }

            return $payload;
        }

        return false;
    }
1213631
public function sign($contents, $privateKey)
    {
        $rsa = new RSA();
        $rsa->loadKey($privateKey);

        $rsa->setSignatureMode(RSA::SIGNATURE_PKCS1);

        return $rsa->sign($contents);
    }
464390
private function signUsingRsaSha1($baseString)
    {
        if (!function_exists('openssl_pkey_get_private')) {
            throw new \RuntimeException('RSA-SHA1 signature method '
                . 'requires the OpenSSL extension.');
        }

        $privateKey = openssl_pkey_get_private(
            file_get_contents($this->config['private_key_file']),
            $this->config['private_key_passphrase']
        );

        $signature = '';
        openssl_sign($baseString, $signature, $privateKey);
        openssl_free_key($privateKey);

        return $signature;
    }
1306306
protected function parseTransactionAccount()
    {
        $account = parent::parseTransactionAccount();
        if ($account !== '') {
            return $account;
        }

        // IBAN
        $transactionData = str_replace('Europese Incasso, doorlopend ', '', $this->getCurrentTransactionData());
        $transactionData = preg_replace('![\r\n]+!', '', $transactionData);
        if (preg_match('#/CNTP/(.*?)/#', $transactionData, $results)) {
            $account = trim($results[1]);
            if (!empty($account)) {
                return $this->sanitizeAccount($account);
            }
        }
        if (preg_match('#:86:([A-Z]{2}[\d]{2}[A-Z]{4}[\d]+?) [A-Z]{6}[A-Z0-9]{0,4} #', $transactionData, $results)) {
            $account = trim($results[1]);
            if (!empty($account)) {
                return $this->sanitizeAccount($account);
            }
        }

        return '';
    }
585050
public function signature ( $request, $base_string, $consumer_secret, $token_secret )
	{
		// Fetch the private key cert based on the request
		$cert = $this->fetch_private_cert($request);
		
		// Pull the private key ID from the certificate
		$privatekeyid = openssl_get_privatekey($cert);
		
		// Sign using the key
		$sig = false;
		$ok  = openssl_sign($base_string, $sig, $privatekeyid);   
		
		// Release the key resource
		openssl_free_key($privatekeyid);
		  
		return $request->urlencode(base64_encode($sig));
	}
431597
private function getCurrentConstantKeyFromClassTokens($tokens)
    {
        $parsingStateConstDeclarationFound = false;
        $constDeclarationKey = 0;

        foreach ($tokens as $key => $token) {
            if (is_array($token) === true && $token[0] === T_CONST) {
                $parsingStateConstDeclarationFound = true;
                $constDeclarationKey = $key;
            }

            if ($parsingStateConstDeclarationFound === true && $token[0] === T_STRING) {
                if ($token[1] === $this->getName()) {
                    break;
                } else {
                    $parsingStateConstDeclarationFound = false;
                }
            }
        }

        return $constDeclarationKey;
    }
110553
public function calculateAgreementKey(JWKInterface $private_key, JWKInterface $public_key)
    {
        switch ($public_key->get('crv')) {
            case 'P-256':
            case 'P-384':
            case 'P-521':
                $p = $this->getGenerator($private_key);

                $rec_x = $this->convertBase64ToDec($public_key->get('x'));
                $rec_y = $this->convertBase64ToDec($public_key->get('y'));
                $sen_d = $this->convertBase64ToDec($private_key->get('d'));

                $priv_key = $p->getPrivateKeyFrom($sen_d);
                $pub_key = $p->getPublicKeyFrom($rec_x, $rec_y);

                $message = new MessageFactory(EccFactory::getAdapter());
                $exchange = $priv_key->createExchange($message, $pub_key);

                return $this->convertDecToBin($exchange->calculateSharedKey());
            case 'X25519':
                return curve25519_shared(
                    Base64Url::decode($private_key->get('d')),
                    Base64Url::decode($public_key->get('x'))
                );
            default:
                throw new \InvalidArgumentException(sprintf('The curve "%s" is not supported', $public_key->get('crv')));
        }
    }
11167
public function privateKeyToDer($privateKey, $privateKyePassword = '')
    {
        try {
            if (strlen($privateKyePassword) === 0) {
                return CryptoVirgilKeyPair::privateKeyToDER($privateKey);
            }

            return CryptoVirgilKeyPair::privateKeyToDER(
                $this->encryptPrivateKey($privateKey, $privateKyePassword),
                $privateKyePassword
            );
        } catch (Exception $exception) {
            throw new PrivateKeyToDerConvertingException($exception->getMessage(), $exception->getCode());
        }
    }
556872
function useNonce($server_url, $timestamp, $salt)
    {
        global $Auth_OpenID_SKEW;
        
        // save one request to memcache when nonce obviously expired 
        if (abs($timestamp - time()) > $Auth_OpenID_SKEW) {
            return false;
        }
        
        // SETNX will set the value only of the key doesn't exist yet.
        $nonceKey = $this->nonceKey($server_url, $salt);
        $added = $this->redis->setnx($nonceKey, "1");
        if ($added) {
            // Will set expiration
            $this->redis->expire($nonceKey, $Auth_OpenID_SKEW);
            return true;
        } else {
            return false;
        }
    }
468044
public function decryptPrivateKey($privateKey, $privateKeyPassword)
    {
        try {
            return CryptoVirgilKeyPair::decryptPrivateKey($privateKey, $privateKeyPassword);
        } catch (Exception $exception) {
            throw new PrivateKeyDecryptionException($exception->getMessage(), $exception->getCode());
        }
    }
32072
public function createNew(
        string $providerName,
        string $credentialPubKey,
        string $accessToken,
        string $tokenSecret = '',
        string $signupHash = ''
    ) : array {

        $array = [
            'provider'     => $providerName,
            'access_token' => $accessToken,
            'credential'   => $credentialPubKey
        ];

        if (! empty($tokenSecret)) {
            $array['token_secret'] = $tokenSecret;
        }

        if (! empty($signupHash)) {
            $array['signup_hash'] = $signupHash;
        }

        return $this->sendPost(
            '/sso',
            [],
            $array
        );
    }
852100
public function encrypt($unencrypted)
    {
        if (!is_scalar($unencrypted)) {
            throw new CryptoException(sprintf(self::ERR_CANNOT_ENCRYPT, gettype($unencrypted)));
        }

        // Generate 24 byte nonce
        $nonce = random_bytes(self::NONCE_SIZE_BYTES);

        // Encrypt payload
        try {
            $encrypted = $this->sodiumSecretBox($unencrypted, $nonce, $this->cryptoSecret->getValue());
        } catch (Exception $ex) {
            throw new CryptoException(sprintf(self::ERR_ENCRYPT, $ex->getMessage()), $ex->getCode(), $ex);
        }

        // Calculate MAC
        try {
            $mac = $this->sodiumCryptoAuth($nonce . $encrypted, $this->authSecret->getValue());
        } catch (Exception $ex) {
            throw new CryptoException(sprintf(self::ERR_ENCODE, $ex->getMessage()), $ex->getCode(), $ex);
        }

        // Return appended binary string
        return $nonce . $mac . $encrypted;
    }
877860
public function convertToJWT(CryptKey $privateKey)
    {
        $tokenBuilder = (new Builder())
            ->setAudience($this->getClient()->getIdentifier())
            ->setId($this->getIdentifier(), true)
            ->setIssuedAt(time())
            ->setNotBefore(time())
            ->setExpiration($this->getExpiryDateTime()->getTimestamp())
            ->setSubject($this->getUserIdentifier())
            ->set('scopes', $this->getScopes());

        // add user name to claims
        if ($this->getUserIdentifier()) {
            $userEntity = $this->getUserEntity();
            $member = $userEntity->getMember();

            $tokenBuilder->set('fn', $member ? $member->FirstName : null)
                ->set('ln', $member ? $member->Surname : null);
        }

        return $tokenBuilder->sign(new Sha256(), new Key($privateKey->getKeyPath(), $privateKey->getPassPhrase()))
            ->getToken();
    }
637664
public function invalidateToken()
    {
      $decoded = (array) $this->getDecoded();
      $decoded['data'] = (array) $decoded['data'];
      $this->decoded = null;

      $issuedAt   = time() - $this->expire_after - 7200; // less {expiry} and 2 hours
      $notBefore  = $issuedAt + 10; //Adding 10 seconds - no need, I know
      $expire     = $notBefore + 1; //Adding 1 second - no need, I know

      $decoded["iat"] = $issuedAt;
      $decoded["nbf"] = $notBefore;
      $decoded["exp"] = $expire;


      return $this->token = JWT::encode($decoded, $this->key, 'HS512');

    }
325309
public function signTokenRequest(TokenRequest $tokenRequest, $privateKey)
    {
        openssl_sign($tokenRequest->getIssuer() . ':' . $tokenRequest->getUsername(), $signature, $privateKey);

        return $tokenRequest->setSignature(base64_encode($signature));
    }
671678
private function getSign($nonce,$timestamp,$token)
	{
		$array = array($nonce,$timestamp,$token);
		sort($array);
		$sign = sha1(implode($array));
		return $sign;
	}