Decrypt a message with your secret key, that had been encrypted with
your public key by the other endpoint, then get the body as a string.

@param RequestInterface $request
@param SealingSecretKey $secretKey
@return string
@throws InvalidMessageException
336362
public function unsealStringRequest(
        RequestInterface $request,
        SealingSecretKey $secretKey
    ): string {
        $body = Base64UrlSafe::decode((string) $request->getBody());
        return Simple::unseal(
            $body,
            $secretKey
        );
    }
1190909
public function execute(RequestInterface $request): RequestInterface
    {
        $body = $request->getBody()->getContents();

        $iv = random_bytes(self::INITIATION_VECTOR_LENGTH);
        $aesKey = random_bytes(self::AES_KEY_LENGTH);
        $encryptedAesKey = $this->publicKey->encrypt($aesKey);
        $bodyEncrypted = $this->determineBodyStringEncrypted($body, $aesKey, $iv);
        $hmac = $this->determineHmac($aesKey, $iv, $bodyEncrypted);
        $encryptedHeaders = [
            self::HEADER_CLIENT_ENCRYPTION_IV => [base64_encode($iv)],
            self::HEADER_CLIENT_ENCRYPTION_KEY => [base64_encode($encryptedAesKey)],
            self::HEADER_CLIENT_ENCRYPTION_HMAC => [base64_encode($hmac)],
        ];

        return new Request(
            $request->getMethod(),
            $request->getUri(),
            array_merge($request->getHeaders(), $encryptedHeaders),
            $bodyEncrypted
        );
    }
1094167
public function decrypt($text, $key = null)
    {
        if (!function_exists('openssl_cipher_iv_length')) {
            throw new RuntimeException('openssl extension is required');
        }

        if ($key === null) {
            $decryptKey = $this->key;
        } else {
            $decryptKey = $key;
        }

        if (empty($decryptKey)) {
            throw new InvalidArgumentException('Decryption key cannot be empty');
        }

        $cipher = $this->cipher;
        $mode   = strtolower(substr($cipher, strrpos($cipher, '-') - strlen($cipher)));

        if (!in_array($cipher, openssl_get_cipher_methods(true))) {
            throw new UnexpectedValueException("Cipher algorithm is unknown [$cipher]");
        }

        $ivSize = openssl_cipher_iv_length($cipher);
        if ($ivSize > 0) {
            $blockSize = $ivSize;
        } else {
            $blockSize = openssl_cipher_iv_length(str_ireplace('-' . $mode, '', $cipher));
        }

        $decrypted = openssl_decrypt(substr($text, $ivSize), $cipher, $decryptKey, OPENSSL_RAW_DATA, substr($text, 0, $ivSize));

        $paddingType = $this->padding;

        if ($mode === 'cbc' || $mode === 'ecb') {
            return $this->unpadText($decrypted, $mode, $blockSize, $paddingType);
        }

        return $decrypted;
    }
737907
public static function seal(
        string $plaintext,
        SealingPublicKey $publicKey
    ): string {
        $ephemeralSecret = SealingSecretKey::generate();
        $sharedSecret = static::keyExchange(
            $ephemeralSecret,
            $publicKey,
            false,
            56
        );
        $ephemeralPublicKey = $ephemeralSecret->getPublickey()->getString(true);
        $sharedKey = \ParagonIE_Sodium_Core_Util::substr($sharedSecret, 0, 32);
        $nonce = \ParagonIE_Sodium_Core_Util::substr($sharedSecret, 32, 24);
        try {
            \ParagonIE_Sodium_Compat::memzero($sharedSecret);
        } catch (\Throwable $ex) {
        }

        return $ephemeralPublicKey. \ParagonIE_Sodium_Compat::crypto_aead_xchacha20poly1305_ietf_encrypt(
            $plaintext,
            $ephemeralPublicKey,
            $nonce,
            $sharedKey
        );
    }
456996
private function getCacheKey(ServerRequestInterface $request)
    {
        $id = base64_encode((string) $request->getUri());
        $hints = $this->getClientHints($request);

        if ($hints) {
            $id .= '.'.base64_encode(json_encode($hints));
        }

        return $id;
    }
477190
public static function fromSealed(
        PasswordInterface $password,
        string $sealed,
        bool $validate = true,
        callable $keyProvider = null,
        callable $saltGenerator = null
    ): Token {
        $parts = explode('*', $sealed);
        if (count($parts) !== 8) {
            throw new InvalidTokenException('Invalid token structure.');
        }

        list($version, $pwId, $salt, $iv, $cipherText, $ttd, $macSalt, $mac)
            = $parts;

        if ($version !== Token::MAC_PREFIX . Token::MAC_FORMAT_VERSION) {
            throw new InvalidTokenException('Invalid token version.');
        }

        if ($pwId !== $password->getId()) {
            throw new PasswordMismatchException(
                $password->getId(), 
                $pwId, 
                "Token encrypted with password $pwId; password"
                    . " {$password->getId()} provided for validation."
            );
        }

        $token = new self(
            $password,
            $salt,
            base64_decode($iv),
            base64_decode($cipherText),
            $ttd,
            $keyProvider,
            $saltGenerator
        );

        if ($validate) {
            if ($token->isExpired()) {
                throw new ExpiredTokenException('Token expired on '
                    . DateTime::createFromFormat('U', $ttd)->format('c'));
            }

            $token->validateChecksum($macSalt, $mac);
        }

        return $token;
    }
1074020
protected function checkSecurity(Request $request, $secret)
    {
        // Reset any previously payload set.
        $this->eventName = $this->payload = $this->delivery = null;

        // Extract Github headers from request.
        $signature = (string) $request->headers->get('X-Hub-Signature');
        $event = (string) $request->headers->get('X-Github-Event');
        $delivery = (string) $request->headers->get('X-Github-Delivery');
        $payload = (string) $request->getContent();

        if (empty($signature) || empty($event) || empty($delivery)) {
            throw new \InvalidArgumentException('Missing Github headers.');
        }

        if ($this->validateSignature($secret, $signature, $payload)) {
            $this->eventName = $event;
            $this->payload = $payload;
            $this->delivery = $delivery;

            return true;
        }

        return false;
    }
977210
public static final String decrypt(String secretKey, String encryptedText) {
        if (encryptedText == null) {
            return null;
        }
        if (encryptedText.startsWith("$CRYPT::")) { //$NON-NLS-1$
            byte[] decoded = Base64.decodeBase64(encryptedText.substring(8));
            Cipher cipher;
            try {
                SecretKeySpec skeySpec = keySpecFromSecretKey(secretKey);
                
                cipher = Cipher.getInstance("AES"); //$NON-NLS-1$
                cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) {
                throw new RuntimeException(e);
            }
            try {
                return new String(cipher.doFinal(decoded));
            } catch (IllegalBlockSizeException | BadPaddingException e) {
                throw new RuntimeException(e);
            }
        } else {
            return encryptedText;
        }
    }
676596
public static function unseal(
        string $ciphertext,
        SealingSecretKey $secretKey
    ): string {
        $ephemeralPublicKey = \ParagonIE_Sodium_Core_Util::substr($ciphertext, 0, 32);

        $sharedSecret = static::keyExchange(
            $secretKey,
            new SealingPublicKey($ephemeralPublicKey),
            true,
            56
        );
        $sharedKey = \ParagonIE_Sodium_Core_Util::substr($sharedSecret, 0, 32);
        $nonce = \ParagonIE_Sodium_Core_Util::substr($sharedSecret, 32, 24);
        try {
            \ParagonIE_Sodium_Compat::memzero($sharedSecret);
        } catch (\Throwable $ex) {
        }

        $plaintext = \ParagonIE_Sodium_Compat::crypto_aead_xchacha20poly1305_ietf_decrypt(
            \ParagonIE_Sodium_Core_Util::substr($ciphertext, 32),
            $ephemeralPublicKey,
            $nonce,
            $sharedKey
        );
        if (!\is_string($plaintext)) {
            throw new InvalidMessageException('Incorrect message authentication tag');
        }
        return $plaintext;
    }
607938
public function encrypt($plaintext, $key) {
		$crypt_aes = $this->setupAES256($key);

		return $crypt_aes->encrypt($plaintext);
	}
1192188
private function encryptorFactory($classFullName, $secretKey) {
        $refClass = new \ReflectionClass($classFullName);
        if ($refClass->implementsInterface(self::ENCRYPTOR_INTERFACE_NS)) {
            return new $classFullName($secretKey);
        } else {
            throw new \RuntimeException('Encryptor must implements interface EncryptorInterface');
        }
    }
845345
public function parseRequest(Request $request, $secret, $dispatch = true)
    {
        if (!$this->checkSecurity($request, $secret)) {
            throw new \InvalidArgumentException('Invalid security checksum header.');
        }

        if ($className = $this->getEventClassName($this->eventName)) {
            $event = new $className($this->eventName, $this->payload, $this->delivery);
        } else {
            throw new \InvalidArgumentException('Unknown event type.');
        }

        if (null !== $this->eventDispatcher && $dispatch) {
            $this->eventDispatcher->dispatch(Events::WEBHOOK_REQUEST, $event);
        }

        return $event;
    }
610390
public function authenticateRequestWithSharedKey(
        RequestInterface $request,
        SharedAuthenticationKey $key
    ): RequestInterface {
        $mac = \ParagonIE_Sodium_Compat::crypto_auth(
            (string) $request->getBody(),
            $key->getString(true)
        );
        return $request->withAddedHeader(
            self::HEADER_AUTH_NAME,
            Base64UrlSafe::encode($mac)
        );
    }
766495
public function decryptRequestWithSharedKey(
        RequestInterface $request,
        SharedEncryptionKey $key
    ): RequestInterface {
        $encrypted = Base64UrlSafe::decode((string) $request->getBody());
        return $request->withBody(
            $this->adapter->stringToStream(
                Simple::decrypt($encrypted, $key)
            )
        );
    }
1137896
public function decrypt(string $ciphertext, string $key): string
    {
        $numMatches = preg_match_all('%^ENC\[([^,]+),(.*)\]$%', $ciphertext, $matches);
        if (0 == $numMatches) {
            throw new Exception\RuntimeException(sprintf(
                "\$ciphertext must be in the format ENC[\$encryptionType,\$ciphertext].\n"
                . "Provided ciphertext: %s",
                $ciphertext
            ));
        }

        $encryptionType = $matches[1][0];
        $ciphertext = $matches[2][0];

        switch ($encryptionType) {
            case self::ENCRYPTION_TYPE_DEFUSE_PHP_ENCRYPTION:
                $key = Key::loadFromAsciiSafeString($key);
                return Crypto::decrypt($ciphertext, $key);

            default:
                throw new Exception\RuntimeException(sprintf(
                    'Unsupported encryption type "%s". Supported encryption types: "%s".',
                    $encryptionType,
                    implode('", "', [self::ENCRYPTION_TYPE_DEFUSE_PHP_ENCRYPTION])
                ));
        }


    }
80277
public function maskPayload($maskingKey = null) {
        if (null === $maskingKey) {
            $maskingKey = $this->generateMaskingKey();
        }

        if (static::MASK_LENGTH !== strlen($maskingKey)) {
            throw new \InvalidArgumentException("Masking key must be " . static::MASK_LENGTH ." characters");
        }

        if (extension_loaded('mbstring') && true !== mb_check_encoding($maskingKey, 'US-ASCII')) {
            throw new \OutOfBoundsException("Masking key MUST be ASCII");
        }

        $this->unMaskPayload();

        $this->secondByte = $this->secondByte | 128;
        $this->data[1]    = chr($this->secondByte);

        $this->data = substr_replace($this->data, $maskingKey, $this->getNumPayloadBytes() + 1, 0);

        $this->bytesRecvd += static::MASK_LENGTH;
        $this->data        = substr_replace($this->data, $this->applyMask($maskingKey), $this->getPayloadStartingByte(), $this->getPayloadLength());

        return $this;
    }
425106
protected function signRequest(HttpRequest $request, $username, $timestamp, $secretKey)
    {
        $message = $username
                 . $timestamp
                 . $this->getRequestMessage($request)
        ;

        return $this->algorithm->sign($message, $secretKey);
    }