@param $data
@param $privateKey
@param $format

@return string
@throws CryptoException
438657
public static function encryptRsaPrivate(string $data, string $privateKey, string $format = null): string
    {
        $key = \openssl_pkey_get_private($privateKey);

        $encrypted = '';
        if (!\openssl_private_encrypt($data, $encrypted, $key, OPENSSL_PKCS1_OAEP_PADDING)) {
            throw new CryptoException('RSA private encrypt error: ' . openssl_error_string());
        }
        \openssl_pkey_free($key);

        return self::fromRaw($encrypted, $format);
    }
1266589
public function decrypt($data, $key = null, $iv = null)
    {
        $key = $key === null ? $this->privateKey : $key;

        if (strpos($data, ':') !== false) {
            list($hmac, $pbkdf2Salt, $ivFromData, $encrypted) = explode(':', $data);

            $hmac = base64_decode($hmac);
            $pbkdf2Salt = base64_decode($pbkdf2Salt);
            $ivFromData = base64_decode($ivFromData);
            $encrypted = base64_decode($encrypted);

            $iv = $iv ?: $ivFromData;

            $this->derivateSecureKeys($key, $pbkdf2Salt);

            $calculatedHmac = $this->hmac($pbkdf2Salt . $iv . $encrypted);

            if (!$this->equalHashes($calculatedHmac, $hmac)) {
                throw new \RuntimeException('HMAC ERROR: Invalid HMAC.');
            }
        } else {
            // For 3.1 and older legacy
            $data = base64_decode($data);

            if (!$iv) {
                $ivSize = $this->getIVSize();

                $iv = substr($data, 0, $ivSize);

                $encrypted = substr($data, $ivSize);
            } else {
                $ivSize = $this->getIVSize();

                if (substr($data, 0, $ivSize) === $iv) {
                    $encrypted = substr($data, $ivSize);
                } else {
                    $encrypted = $data;
                }
            }
        }

        $key = CryptHelper::repeatToLength($key, 24, true);

        // Decrypt the data.
        return trim($this->doDecrypt($encrypted, $key, $iv));
    }
977952
protected function generateXml(Connect $connect, $privateKey, $data)
    {
        $certificateGen = (new X509CertificateGen())->createX509Certificate($privateKey);

        $certificate = new X509Certificate();
        $certificate->loadPem($certificateGen);

        $builder = new MetadataBuilder();
        $xml = $builder->build($data['entityID'], $data['acs'], $data['logout'], $certificate);

        $path = $connect->getConfig()->getSamlMetadataBaseDir().'/'.$connect->getConfig()->getSpMetadataFile();
        file_put_contents($path, $xml);

        $message = (new SpEntityConfigurationMessage())
            ->setXml($xml);

        $message = (new SignedMessageDecorator($message))
            ->setCertificate((new X509CertificateGen())->createX509Certificate($privateKey))
            ->sign($privateKey);

        $certificate = $connect->getSaml()
            ->getMetadata()
            ->getFirstIdpSsoDescriptor()
            ->getFirstKeyDescriptor(KeyDescriptor::USE_ENCRYPTION)
            ->getCertificate()
            ->toPem();

        return (new MessageResponse($message))->buildEncrypted($certificate);
    }
439368
protected function readPrivateKey(SplFileObject $privateKey)
    {
        $key = '';
        while (!$privateKey->eof()) {
            $key .= $privateKey->fgets();
        }
        return $key;
    }
967604
private function makeSignature($data)
    {
        $signature = '';
        $this->initOpenSSL();
        if (!openssl_sign($data, $signature, $this->privateKey, 'sha256')) {
            throw new SignatureException(openssl_error_string());
        }
        return $signature;
    }
667807
public static function verifyRsa(string $data, string $signature, string $publicKey, string $format = null): bool
    {
        $signature = self::toRaw($signature, $format);
        $key = \openssl_pkey_get_public($publicKey);

        $return = \openssl_verify($data, $signature, $key, OPENSSL_ALGO_SHA256);
        if ($return === -1) {
            throw new CryptoException('RSA signature check error: ' . openssl_error_string());
        }

        return $return === 1;
    }
1268970
public function sign($data)
    {
        if (!ctype_xdigit($this->hex)) {
            throw new \Exception('The private key must be in hex format.');
        }

        if (empty($data)) {
            throw new \Exception('You did not provide any data to sign.');
        }

        $e = Util::decodeHex(hash('sha256', $data));

        do {
            if (substr(strtolower($this->hex), 0, 2) != '0x') {
                $d = '0x'.$this->hex;
            } else {
                $d = $this->hex;
            }

            $k = SecureRandom::generateRandom(32);

            $k_hex = '0x'.strtolower(bin2hex($k));
            $n_hex = '0x'.Secp256k1::N;


            $Gx = '0x'.substr(Secp256k1::G, 2, 64);
            $Gy = '0x'.substr(Secp256k1::G, 66, 64);

            $P = new Point($Gx, $Gy);

            // Calculate a new curve point from Q=k*G (x1,y1)
            $R = Util::doubleAndAdd($k_hex, $P);

            $Rx_hex = Util::encodeHex($R->getX());

            $Rx_hex = str_pad($Rx_hex, 64, '0', STR_PAD_LEFT);

            // r = x1 mod n
            $r = Math::mod('0x'.$Rx_hex, $n_hex);

            // s = k^-1 * (e+d*r) mod n
            $edr  = Math::add($e, Math::mul($d, $r));
            $invk = Math::invertm($k_hex, $n_hex);
            $kedr = Math::mul($invk, $edr);

            $s = Math::mod($kedr, $n_hex);

            // The signature is the pair (r,s)
            $signature = array(
                'r' => Util::encodeHex($r),
                's' => Util::encodeHex($s),
            );

            $signature['r'] = str_pad($signature['r'], 64, '0', STR_PAD_LEFT);
            $signature['s'] = str_pad($signature['s'], 64, '0', STR_PAD_LEFT);
        } while (Math::cmp($r, '0') <= 0 || Math::cmp($s, '0') <= 0);

        $sig = array(
            'sig_rs'  => $signature,
            'sig_hex' => self::serializeSig($signature['r'], $signature['s']),
        );

        return $sig['sig_hex']['seq'];
    }
453079
public function serialize($data, $format = 'json')
    {
        $jsonContent = $this->getJmsSerializer()->serialize($data, $format);

        return $jsonContent;
    }
468044
public function decryptPrivateKey($privateKey, $privateKeyPassword)
    {
        try {
            return CryptoVirgilKeyPair::decryptPrivateKey($privateKey, $privateKeyPassword);
        } catch (Exception $exception) {
            throw new PrivateKeyDecryptionException($exception->getMessage(), $exception->getCode());
        }
    }
936795
public static function rsaPrivateDecrypt(
        $str,
        $privateKeyPath,
        $passPhrase = '',
        $padding = OPENSSL_PKCS1_PADDING,
        $format = self::FORMAT_HEX
    )
    {
        $str = trim($str);

        switch ($format) {
            case self::FORMAT_HEX:
                $str = hex2bin($str);
                break;
            case self::FORMAT_BASE64:
                $str = EncodeHelper::base64Decode($str);
                break;
            default:
                $str = hex2bin($str);
        }

        openssl_private_decrypt(
            $str,
            $decrypted,
            openssl_get_privatekey(file_get_contents($privateKeyPath), $passPhrase),
            $padding
        );

        return trim($decrypted);
    }
730809
public static function encrypt(
        string $plaintext,
        string $key,
        string $ad = '',
        string $format = null,
        bool $password = false
    ): string {
        if (\mb_strlen($key, '8bit') !== self::KEY_BYTE_SIZE) {
            throw new CryptoException('Bad key length.');
        }

        $salt = \random_bytes(self::SALT_BYTE_SIZE);

        [$authKey, $encryptKey] = self::deriveKeys($key, $salt, $password);

        $iv = \random_bytes(self::BLOCK_BYTE_SIZE);

        $ad = self::getAd($ad);

        $tag = '';
        if (self::$sodium) {
            $cipherText = \sodium_crypto_aead_aes256gcm_encrypt($plaintext, $ad, $iv, $encryptKey);
        } else {
            $cipherText = \openssl_encrypt(
                $plaintext,
                self::CIPHER_METHOD,
                $encryptKey,
                \OPENSSL_RAW_DATA,
                $iv, $tag, $ad
            );
        }

        if ($cipherText === false) {
            throw new CryptoException('Encrypt failed.');
        }

        $cipherText = self::CURRENT_VERSION . $salt . $iv . $cipherText . $tag;
        $auth = \hash_hmac(self::HASH_TYPE, $cipherText, $authKey, true);
        $cipherText .= $auth;

        return self::fromRaw($cipherText, $format);
    }
133394
public static function encrypt($data, $key) {

        static :: check();
        
        $iv = static :: random_bytes(16);
        
        //Encryption
        $ciphertext = openssl_encrypt($data, self :: METHOD, mb_substr($key, 0, 32, self :: ENCODING), OPENSSL_RAW_DATA, $iv);

        //Authentication
        $hmac = hash_hmac(self :: ALGORITHM, $iv . $ciphertext, mb_substr($key, 32, null, self :: ENCODING), true);

        return $hmac . $iv . $ciphertext;
    }
522962
public static function toRaw(string $raw, string $format = null): string
    {
        $format = $format ?? self::$format;

        switch ($format) {
            case self::FORMAT_HEX:
                return \hex2bin($raw);

            case self::FORMAT_BASE64:
                return \base64_decode($raw);

            case self::FORMAT_STR:
                return \hex2bin(\str_replace('\x', '', $raw));

            case self::FORMAT_RAW:
                return $raw;

            default:
                throw new InvalidArgumentException("Crypto return format not defined: $format");
        }
    }
815528
public function encryptByPublicKey_data($data, $publickey = '')
	{
		$RSACrypt = new RSACrypt();

		if ($publickey != "") {
			$RSACrypt->pubkey = $publickey;
		}
		$crypt_res = "";
		for ($i = 0; $i < ((strlen($data) - strlen($data) % 117) / 117 + 1); $i++) {
			$crypt_res = $crypt_res . ($RSACrypt->encryptByPublicKey(mb_strcut($data, $i * 117, 117, 'utf-8')));
		}
		return $crypt_res;
	}
980921
public function decrypt($data){
        $data = base64_decode($data);
        $maxlength = $this->getMaxDecryptBlockSize($this->privateKey);
        $output='';
        while(strlen($data)){
            $input = substr($data, 0, $maxlength);
            $data = substr($data, $maxlength);
            openssl_private_decrypt($input, $out, $this->privateKey);
            $output .= $out;
        }
        return $output;
    }
1305805
public function aes128EcbEncrypt($key, $data, $iv)
    {
        if (16 !== strlen($key)) {
            $key = hash('MD5', $key, TRUE);
        }
        if (16 !== strlen($iv)) {
            $iv = hash('MD5', $iv, TRUE);
        }
        $padding = 16 - (strlen($data) % 16);
        $data    .= str_repeat(chr($padding), $padding);
        $result  = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_ECB, $iv);

        return $result;
    }
517793
private function getOpenSSLSignature(JWKInterface $key, $data)
    {
        $pem = (new ECKey($key))->toPEM();
        $result = openssl_sign($data, $signature, $pem, $this->getHashAlgorithm());

        Assertion::true($result, 'Signature failed');

        $asn = ASNObject::fromBinary($signature);
        Assertion::isInstanceOf($asn, Sequence::class, 'Invalid signature');

        $res = '';
        foreach ($asn->getChildren() as $child) {
            Assertion::isInstanceOf($child, Integer::class, 'Invalid signature');
            $res .= str_pad($this->convertDecToHex($child->getContent()), $this->getSignaturePartLength(), '0', STR_PAD_LEFT);
        }

        return $this->convertHexToBin($res);
    }