Encrypts private key with a password.

@param string $privateKey
@param string $password

@return string

@throws PrivateKeyEncryptionException
323361
public function encryptPrivateKey($privateKey, $password)
    {
        try {
            return CryptoVirgilKeyPair::encryptPrivateKey($privateKey, $password);
        } catch (Exception $exception) {
            throw new PrivateKeyEncryptionException($exception->getMessage(), $exception->getCode());
        }
    }
1010377
public function sign($key, $password = null)
    {
        OpenSslException::reset();

        if (false === extension_loaded('openssl')) {
            // @codeCoverageIgnoreStart
            throw OpenSslException::create(
                'The "openssl" extension is not available.'
            );
            // @codeCoverageIgnoreEnd
        }

        if (false === ($resource = openssl_pkey_get_private($key, $password))) {
            // @codeCoverageIgnoreStart
            throw OpenSslException::lastError();
            // @codeCoverageIgnoreEnd
        }

        if (false === openssl_pkey_export($resource, $private)) {
            // @codeCoverageIgnoreStart
            throw OpenSslException::lastError();
            // @codeCoverageIgnoreEnd
        }

        if (false === ($details = openssl_pkey_get_details($resource))) {
            // @codeCoverageIgnoreStart
            throw OpenSslException::lastError();
            // @codeCoverageIgnoreEnd
        }

        $this->phar->setSignatureAlgorithm(Phar::OPENSSL, $private);

        if (false === @file_put_contents($this->file . '.pubkey', $details['key'])) {
            throw FileException::lastError();
        }
    }
614155
public static byte[] decryptBytes (PrivateKey key, byte[] encrypted, byte[] salt)
    {
        try {
            byte[] decrypted = getRSACipher(key).doFinal(encrypted);
            for (int ii = 0; ii < salt.length; ii++) {
                if (decrypted[decrypted.length - salt.length + ii] != salt[ii]) {
                    return null;
                }
            }
            byte[] secret = new byte[decrypted.length - salt.length];
            for (int ii = 0; ii < secret.length; ii++) {
                secret[ii] = decrypted[ii];
            }
            return secret;
        } catch (GeneralSecurityException gse) {
            log.warning("Failed to decrypt bytes", gse);
        }
        return null;
    }
1341230
public function extractPublicKey($private, $passphrase = null)
    {
        $this->clearBufferedMessages();

        if (false === ($resource = openssl_pkey_get_private($private, $passphrase))) {
            throw new RuntimeException(sprintf(
                'The private key could not be processed: %s',
                openssl_error_string()
            ));
        }

        if (false === ($details = openssl_pkey_get_details($resource))) {
            throw new RuntimeException(sprintf(
                'The details of the private key could not be extracted: %s',
                openssl_error_string()
            ));
        }

        openssl_free_key($resource);

        return $details['key'];
    }
338691
public static String encrypt(final String password) throws AuthenticationException {
        String hashValue;
        try {
            final MessageDigest msgDigest = MessageDigest.getInstance("SHA");
            msgDigest.update(password.getBytes("UTF-8"));
            final byte rawByte[] = msgDigest.digest();
            hashValue = new String(Base64.encodeBase64(rawByte));

        } catch (Exception e) {
            LOG.error("Encryption failed.");
            throw new AuthenticationException("Error occurred during password encryption", e);
        }

        return hashValue;
    }
931225
public static function loadFromString(string $content, $password = NULL): PrivateKey {
        $handle = openssl_pkey_get_private($content, $password);
        if(!$handle) {
            throw new RuntimeException(OpenSSL::getLastError());
        }
        return new PrivateKey($handle);
    }
1175657
private function decryptWithPrivateKey($cipher, OpenSslRsaKey $privateKey)
    {
        $decrypted = '';
        $key = openssl_pkey_get_private($privateKey->getKeyString());
        if (openssl_private_decrypt($cipher, $decrypted, $key, $this->paddingAlgorithm) === false) {
            // Fallback for data that was encrypted with old default OPENSSL_PKCS1_PADDING
            if ($this->paddingAlgorithm !== OPENSSL_PKCS1_PADDING) {
                if (openssl_private_decrypt($cipher, $decrypted, $key, OPENSSL_PKCS1_PADDING) !== false) {
                    return $decrypted;
                }
            }
            $openSslErrors = [];
            while (($errorMessage = openssl_error_string()) !== false) {
                $openSslErrors[] = $errorMessage;
            }
            throw new SecurityException(sprintf('Decryption failed, OpenSSL error: %s', implode(chr(10), $openSslErrors)), 1556609762);
        }

        return $decrypted;
    }
706021
public function encrypt($encrypt, $key)
    {
        $inputParams = [
            'encrypt' => $encrypt,
            'key'     => $key,
        ];
        $this->debug->info(__FUNCTION__, 'Input Params: ' . json_encode($inputParams));
        $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB), MCRYPT_RAND);
        $this->debug->debug(__FUNCTION__, 'IV Key: ' . json_encode($iv));
        $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, pack("H*", $key), $encrypt, MCRYPT_MODE_ECB, $iv));
        $this->debug->info(__FUNCTION__, 'encrypt Result: ' . json_encode($encrypted));

        return $encrypted;
    }
866924
public function encrypt(string $data, string $password): string
    {
        $iv = $this->generateInitializationVector();
        $encryptedData = openssl_encrypt($data, self::CYPHER, $password, self::OPTIONS, $iv);
        if (false === $encryptedData) {
            $messages = [];
            while ($message = openssl_error_string()) {
                $messages[] = $message;
            }

            throw new CryptException('openssl_encrypt returned an error: '.implode(', ', $messages));
        }

        return $encryptedData.':'.bin2hex($iv);
    }
309172
public function setPassword($password)
    {
        $this->password    = $password;
        $encryptedPassword = $this->getEncryptedPassword($password, $this->getSecret(), $this->getRequestAuthenticator());

        $this->setAttribute(2, $encryptedPassword);

        return $this;
    }
1072368
public function encrypt($password, $data)
    {
        $salt = substr(md5(mt_rand(), true), 8);
        $key = md5($password . $salt, true);
        $iv  = md5($key . $password . $salt, true);
        $ct = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);
        return base64_encode('Salted__' . $salt . $ct);
    }
942896
public function getOpenSslEncryptor(int $cipher, string $password): OpenSslEncryptor {
        if (false === extension_loaded('openssl')) {
            throw new \Exception('OpenSSL Extension not available');
        }
        $encryptor = new OpenSslEncryptor($cipher, $password);
        if (false === $encryptor->isEncryptionCipherSupported($cipher)) {
            throw new \Exception('Trying to use unsupported encryption cipher');
        }
        return $encryptor;
    }
1133757
public PrivateKey getPrivateKeyFromString(String key) throws MangooEncryptionException {
        Objects.requireNonNull(key, Required.KEY.toString());
        
        try {
            return KeyFactory.getInstance(ALGORITHM).generatePrivate(new PKCS8EncodedKeySpec(decodeBase64(key)));
        } catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
            throw new MangooEncryptionException("Failed to get private key from string", e);
        }
    }
886037
private function _encrypt($input, $password, $iv = null)
    {
        return (self::$allowedCiphers[$this->cipher]['iv'])
            ? openssl_encrypt($input, $this->cipher, $password, true, $iv)
            : openssl_encrypt($input, $this->cipher, $password, true);
    }
77279
public function encrypt($string, $key)
    {
        try {
            return $this->driverInstance->encrypt($string, $key);
        } catch (\Exception $e) {
            throw new CryptException($e->getMessage());
        }
    }
322329
public function generateTokenSignature($data, PrivateKey $privateKey)
    {
        if (!$privateKey instanceof VirgilPrivateKey) {
            throw new VirgilCryptoException("instance of VirgilPrivateKey expected");
        }

        return $this->virgilCrypto->generateSignature($data, $privateKey);
    }
307147
private function decryptPrivateKey(PKIPrivateKey $pkiKey)
    {
        // Get the symmetric key used to encrypt the private key of the user
        $encryptedKey = base64_decode($pkiKey->getKey());

        $privateMasterKey = $this->getPrivateMasterKey();
        $symmetricKey = $this->cryptographyProvider->decryptWithPrivateKey($encryptedKey, $privateMasterKey);

        if ($symmetricKey) {
            // Decrypt the private key of the user
            $iv = $pkiKey->getIv();
            $keyData = new KeyData($symmetricKey, $iv);

            $encryptedUserPrivateKey = $pkiKey->getPrivateKey();
            $userPrivateKey = $this->cryptographyProvider->decrypt($encryptedUserPrivateKey, $keyData);

            return $userPrivateKey;
        }
        else {
            throw new EncryptionException('Could not retrieve the encryption keys of the user');
        }
    }