Like libsodium's crypto_kx() but supports an arbitrary output length
in the range (16 <= N <= 64).

@param SealingSecretKey $secretKey
@param SealingPublicKey $publicKey
@param bool $serverSide
@param int $outputLength
@return string
975566
public static function keyExchange(
        SealingSecretKey $secretKey,
        SealingPublicKey $publicKey,
        bool $serverSide,
        int $outputLength = 32
    ): string {
        if ($serverSide) {
            $suffix = $publicKey->getString(true) .
                $secretKey->getPublickey()->getString(true);
        } else {
            $suffix = $secretKey->getPublickey()->getString(true) .
                $publicKey->getString(true);
        }
        return \ParagonIE_Sodium_Compat::crypto_generichash(
            \ParagonIE_Sodium_Compat::crypto_scalarmult(
                $secretKey->getString(true),
                $publicKey->getString(true)
            ) . $suffix,
            '',
            $outputLength
        );
    }
955922
public function encrypt(string $plainText, ContentEncryptionKey $contentEncryptionKey, Nonce $nonce, Salt $salt, PublicKey $senderPublicKey) : Cipher
    {
        $encryptedText = openssl_encrypt($plainText, 'aes-128-gcm', $contentEncryptionKey->getRawKeyMaterial(), OPENSSL_RAW_DATA, $nonce->getRawBytes(), $tag);

        $cipherText = new CipherText(new BinaryString($encryptedText));
        $tag = new AuthenticationTag(new BinaryString($tag));

        return new Cipher($cipherText, $tag, $salt, $senderPublicKey);
    }
344426
public static function verifyWithPSS(RSAKey $key, string $message, string $signature, string $hash): bool
    {
        if (\mb_strlen($signature, '8bit') !== $key->getModulusLength()) {
            throw new \InvalidArgumentException();
        }
        $s2 = BigInteger::createFromBinaryString($signature);
        $m2 = RSAKey::exponentiate($key, $s2);
        $em = self::convertIntegerToOctetString($m2, $key->getModulusLength());
        $modBits = 8 * $key->getModulusLength();

        return self::verifyEMSAPSS($message, $em, $modBits - 1, Hash::$hash());
    }
491469
public static function serializePublicKey(PublicKey $publicKey): string
    {
        $hexString = '04';
        $hexString .= str_pad(gmp_strval($publicKey->getPoint()->getX(), 16), 64, '0', STR_PAD_LEFT);
        $hexString .= str_pad(gmp_strval($publicKey->getPoint()->getY(), 16), 64, '0', STR_PAD_LEFT);

        return $hexString;
    }
667210
public static function verifyWebhookSignature($signature, $message, $secretKey)
    {
        $data = "";

        if (is_string($message)) {
            $data = $message;
        } else {
            $data = json_encode($message);
        }
        return hash_hmac("sha256", $data, $secretKey) == $signature;
    }
8695
public static byte[] encryptBytes (PublicKey key, byte[] secret, byte[] salt)
    {
        byte[] encrypt = new byte[secret.length + salt.length];
        for (int ii = 0; ii < secret.length; ii++) {
            encrypt[ii] = secret[ii];
        }
        for (int ii = 0; ii < salt.length; ii++) {
            encrypt[secret.length + ii] = salt[ii];
        }
        try {
            return getRSACipher(key).doFinal(encrypt);
        } catch (GeneralSecurityException gse) {
            log.warning("Failed to encrypt bytes", gse);
        }
        return encrypt;
    }
733601
function secretKey(length, options = {}) {
  if (!length || length < 1) {
    return '';
  }

  if (!options.crypto || typeof options.crypto.randomBytes !== 'function') {
    throw new Error('Expecting options.crypto to have a randomBytes function');
  }

  return options.crypto
    .randomBytes(length)
    .toString('base64') // convert format
    .slice(0, length); // return required number of characters
}
946231
public static int getKeyLength(final PrivateKey privateKey)
	{
		int length = -1;
		if (privateKey == null)
		{
			return length;
		}
		if (privateKey instanceof RSAPrivateKey)
		{
			length = ((RSAPrivateKey)privateKey).getModulus().bitLength();
		}
		if (privateKey instanceof DSAPrivateKey)
		{
			length = ((DSAPrivateKey)privateKey).getParams().getQ().bitLength();
		}
		if (privateKey instanceof ECPrivateKey)
		{
			length = ((ECPrivateKey)privateKey).getParams().getCurve().getField().getFieldSize();
		}
		return length;
	}
231369
public function getQRCodeInlineV1($company, $holder, $secret, $size = 200, $encoding = 'utf-8')
    {
        $url = $this->getQRCodeUrl($company, $holder, $secret);

        $renderer = $this->imageBackEnd;
        $renderer->setWidth($size);
        $renderer->setHeight($size);

        $bacon = new BaconQrCodeWriter($renderer);
        $data = $bacon->writeString($url, $encoding);

        if ($this->imageBackEnd instanceof Png) {
            return 'data:image/png;base64,'.base64_encode($data);
        }
        return $data;
    }
626543
function _convertPublicKey($n, $e)
    {
        $signed = $this->publicKeyFormat != self::PUBLIC_FORMAT_XML;

        $modulus = $n->toBytes($signed);
        $publicExponent = $e->toBytes($signed);

        switch ($this->publicKeyFormat) {
            case self::PUBLIC_FORMAT_RAW:
                return array('e' => $e->copy(), 'n' => $n->copy());
            case self::PUBLIC_FORMAT_XML:
                return "<RSAKeyValue>\r\n" .
                       '  <Modulus>' . base64_encode($modulus) . "</Modulus>\r\n" .
                       '  <Exponent>' . base64_encode($publicExponent) . "</Exponent>\r\n" .
                       '</RSAKeyValue>';
                break;
            case self::PUBLIC_FORMAT_OPENSSH:
                // from <http://tools.ietf.org/html/rfc4253#page-15>:
                // string    "ssh-rsa"
                // mpint     e
                // mpint     n
                $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus);
                $RSAPublicKey = 'ssh-rsa ' . base64_encode($RSAPublicKey) . ' ' . $this->comment;

                return $RSAPublicKey;
            default: // eg. self::PUBLIC_FORMAT_PKCS1_RAW or self::PUBLIC_FORMAT_PKCS1
                // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.1>:
                // RSAPublicKey ::= SEQUENCE {
                //     modulus           INTEGER,  -- n
                //     publicExponent    INTEGER   -- e
                // }
                $components = array(
                    'modulus' => pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($modulus)), $modulus),
                    'publicExponent' => pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($publicExponent)), $publicExponent)
                );

                $RSAPublicKey = pack(
                    'Ca*a*a*',
                    self::ASN1_SEQUENCE,
                    $this->_encodeLength(strlen($components['modulus']) + strlen($components['publicExponent'])),
                    $components['modulus'],
                    $components['publicExponent']
                );

                if ($this->publicKeyFormat == self::PUBLIC_FORMAT_PKCS1_RAW) {
                    $RSAPublicKey = "-----BEGIN RSA PUBLIC KEY-----\r\n" .
                                    chunk_split(base64_encode($RSAPublicKey), 64) .
                                    '-----END RSA PUBLIC KEY-----';
                } else {
                    // sequence(oid(1.2.840.113549.1.1.1), null)) = rsaEncryption.
                    $rsaOID = pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA
                    $RSAPublicKey = chr(0) . $RSAPublicKey;
                    $RSAPublicKey = chr(3) . $this->_encodeLength(strlen($RSAPublicKey)) . $RSAPublicKey;

                    $RSAPublicKey = pack(
                        'Ca*a*',
                        self::ASN1_SEQUENCE,
                        $this->_encodeLength(strlen($rsaOID . $RSAPublicKey)),
                        $rsaOID . $RSAPublicKey
                    );

                    $RSAPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" .
                                     chunk_split(base64_encode($RSAPublicKey), 64) .
                                     '-----END PUBLIC KEY-----';
                }

                return $RSAPublicKey;
        }
    }
77166
public function getQRCodeInline($company, $holder, $secret, $size = 200, $encoding = 'utf-8')
    {
        return $this->getBaconQRCodeVersion() === 1
            ? $this->getQRCodeInlineV1($company, $holder, $secret, $size, $encoding)
            : $this->getQRCodeInlineV2($company, $holder, $secret, $size, $encoding);
    }
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;
	}
7392
private static function createSignature(
            $appId, $secretId, $secretKey, $expiration, $bucket, $fileId) {
        if (empty($secretId) || empty($secretKey)) {
            return self::AUTH_SECRET_ID_KEY_ERROR;
        }

        $now = time();
        $random = rand();
        $plainText = "a=$appId&k=$secretId&e=$expiration&t=$now&r=$random&f=$fileId&b=$bucket";
        $bin = hash_hmac('SHA1', $plainText, $secretKey, true);
        $bin = $bin.$plainText;

        $signature = base64_encode($bin);

        return $signature;
    }
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;
        }
    }
71817
public static void write(final PublicKey publicKey, final @NonNull OutputStream outputStream)
		throws IOException
	{
		final byte[] publicKeyBytes = publicKey.getEncoded();
		final X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
		outputStream.write(keySpec.getEncoded());
		outputStream.close();
	}
99115
public static function generate_secret(
		$data, $key=null, $length=64
	) {
		if (!$key)
			$key = uniqid() . (string)mt_rand();
		$bstr = $data . $key;
		$bstr = hash_hmac('sha256', $bstr, $key, true);
		$bstr = base64_encode($bstr);
		$bstr = str_replace(['/', '+', '='], '', $bstr);
		return substr($bstr, 0, $length);
	}
510545
function _convertPublicKey($n, $e)
    {
        $signed = $this->publicKeyFormat != CRYPT_RSA_PUBLIC_FORMAT_XML;

        $modulus = $n->toBytes($signed);
        $publicExponent = $e->toBytes($signed);

        switch ($this->publicKeyFormat) {
            case CRYPT_RSA_PUBLIC_FORMAT_RAW:
                return array('e' => $e->copy(), 'n' => $n->copy());
            case CRYPT_RSA_PUBLIC_FORMAT_XML:
                return "<RSAKeyValue>\r\n" .
                       '  <Modulus>' . base64_encode($modulus) . "</Modulus>\r\n" .
                       '  <Exponent>' . base64_encode($publicExponent) . "</Exponent>\r\n" .
                       '</RSAKeyValue>';
                break;
            case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
                // from <http://tools.ietf.org/html/rfc4253#page-15>:
                // string    "ssh-rsa"
                // mpint     e
                // mpint     n
                $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus);
                $RSAPublicKey = 'ssh-rsa ' . base64_encode($RSAPublicKey) . ' ' . $this->comment;

                return $RSAPublicKey;
            default: // eg. CRYPT_RSA_PUBLIC_FORMAT_PKCS1_RAW or CRYPT_RSA_PUBLIC_FORMAT_PKCS1
                // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.1>:
                // RSAPublicKey ::= SEQUENCE {
                //     modulus           INTEGER,  -- n
                //     publicExponent    INTEGER   -- e
                // }
                $components = array(
                    'modulus' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($modulus)), $modulus),
                    'publicExponent' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($publicExponent)), $publicExponent)
                );

                $RSAPublicKey = pack(
                    'Ca*a*a*',
                    CRYPT_RSA_ASN1_SEQUENCE,
                    $this->_encodeLength(strlen($components['modulus']) + strlen($components['publicExponent'])),
                    $components['modulus'],
                    $components['publicExponent']
                );

                if ($this->publicKeyFormat == CRYPT_RSA_PUBLIC_FORMAT_PKCS1_RAW) {
                    $RSAPublicKey = "-----BEGIN RSA PUBLIC KEY-----\r\n" .
                                    chunk_split(base64_encode($RSAPublicKey), 64) .
                                    '-----END RSA PUBLIC KEY-----';
                } else {
                    // sequence(oid(1.2.840.113549.1.1.1), null)) = rsaEncryption.
                    $rsaOID = pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA
                    $RSAPublicKey = chr(0) . $RSAPublicKey;
                    $RSAPublicKey = chr(3) . $this->_encodeLength(strlen($RSAPublicKey)) . $RSAPublicKey;

                    $RSAPublicKey = pack(
                        'Ca*a*',
                        CRYPT_RSA_ASN1_SEQUENCE,
                        $this->_encodeLength(strlen($rsaOID . $RSAPublicKey)),
                        $rsaOID . $RSAPublicKey
                    );

                    $RSAPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" .
                                     chunk_split(base64_encode($RSAPublicKey), 64) .
                                     '-----END PUBLIC KEY-----';
                }

                return $RSAPublicKey;
        }
    }