@param VirgilPrivateKey $privateKey
@param string           $password

@return VirgilPublicKey
@throws VirgilCryptoException
495986
public function extractPublicKey(VirgilPrivateKey $privateKey, $password = '')
    {
        try {
            $publicKeyData = $this->cryptoService->extractPublicKey($privateKey->getValue(), $password);

            return $this->importPublicKey($publicKeyData);
        } catch (Exception $exception) {
            throw new VirgilCryptoException($exception->getMessage());
        }
    }
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();
    }
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);
    }
344099
function(privateKey, password) {
    // Errors
    if (!privateKey || !password) throw new Error('Missing argument !');
    if (!Helpers.isPrivateKeyValid(privateKey)) throw new Error('Private key is not valid !');
    // Processing
    let pass = derivePassSha(password, 20);
    let r = encrypt(privateKey, convert.hex2ua(pass.priv));
    // Result
    return {
        ciphertext: CryptoJS.enc.Hex.stringify(r.ciphertext),
        iv: convert.ua2hex(r.iv)
    };
}
802145
public static function factory($url, $privateKey = null, $publicKey = null) {
        $url = parent::factory($url, $privateKey, $publicKey);
        $query = $url->getQuery();

        // Fetch transformations from string and add them as state
        $transformations = (array) $query->get('t');
        foreach ($query as $key => $value) {
            if (preg_match('#^t\[\d+\]$#', $key)) {
                $transformations[] = $value;
            }
        }

        $transformations = is_array($transformations) ? $transformations : array();

        foreach ($transformations as $transformation) {
            $url->addTransformation($transformation);
        }

        // Extract any extension and set it as state
        $pattern = '#^/users/[^/]+/images/[^\.]+(\.(?<extension>gif|jpg|png))?$#';
        if (preg_match($pattern, $url->getPath(), $match) && isset($match['extension'])) {
            $url->convert($match['extension']);
        }

        // Remove any existing access token (new one will be recreated when toString is called)
        $query->remove('accessToken');

        return $url;
    }
192370
public function hash($content, $privateKey)
    {
        Arguments::define(Boa::string(), Boa::string())
            ->check($content, $privateKey);

        return hash_hmac($this->algorithm, $content, $privateKey);
    }
422968
public function setPrivateKey($privateKey)
    {
        $privateKey = <<<PKEY
-----BEGIN RSA PRIVATE KEY-----
$privateKey
-----END RSA PRIVATE KEY-----
PKEY;

        if (!$privateKey = @openssl_pkey_get_private($privateKey)) {
            throw new \Exception("Invalid private key given.");
        }

        $this->privateKey = $privateKey;
    }
779481
public function addSMIME(string $certificate, string $privateKey): void
    {
        $signer = new SMIMESigner();
        $signer->certificate = $certificate;
        $signer->privateKey = $privateKey;
        $this->set($signer);
    }
932047
public static PrivateKey createPrivateKey(byte[] privateKey) {
    if (privateKey == null) {
      return null;
    }

    try {
      KeyFactory fac = KeyFactory.getInstance("RSA");
      EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKey);
      return fac.generatePrivate(spec);
    }
    catch (NoSuchAlgorithmException e) {
      throw new IllegalStateException(e);
    }
    catch (InvalidKeySpecException e) {
      throw new IllegalStateException(e);
    }
  }
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);
    }
1077500
private PrivateKey readEcPrivateKey(String fileName) throws InvalidKeySpecException, NoSuchAlgorithmException, IOException, NoSuchProviderException
    {
    	StringBuilder sb = new StringBuilder();
    	BufferedReader br = new BufferedReader(new FileReader(fileName));
    	try {
	    	char[] cbuf = new char[1024];
	    	for (int i=0; i <= 10*1024; i++) {
	    		if (!br.ready())
	    			break;
	    		int len = br.read(cbuf, i*1024, 1024);
	    		sb.append(cbuf, 0, len);
	    	}
	    	if (br.ready()) {
	    		throw new IndexOutOfBoundsException("JWK file larger than 10MB");
	    	}
	    	Type mapType = new TypeToken<Map<String, String>>(){}.getType();
	    	Map<String, String> son = new Gson().fromJson(sb.toString(), mapType);
	    	try {
				@SuppressWarnings({ "unchecked", "rawtypes" })
				EllipticCurveJsonWebKey jwk = new EllipticCurveJsonWebKey((Map<String, Object>)(Map)son);
				Base64Encoder enc = new Base64Encoder();
				ByteArrayOutputStream os = new ByteArrayOutputStream();
	        	enc.encode(jwk.getPrivateKey().getEncoded(), 0, jwk.getPrivateKey().getEncoded().length, os);
				return jwk.getPrivateKey();
			} catch (JoseException e1) {
				e1.printStackTrace();
			}
	        return null;
    	} finally {
    		br.close();
    	}
    }
240293
public static function PrivateKeyFromWif($privateWif) {
//        var private_wif = new ByteBuffer(base58.decode(_private_wif));
//        var version = private_wif.readUInt8(0);
//        assert.equal(0x80, version, `Expected version ${0x80}, instead got ${version}`);
//        // checksum includes the version
//        var private_key = private_wif.slice(0, -4);
//        var checksum = private_wif.slice(-4);
//        var new_checksum = hash.sha256(private_key);
//        new_checksum = hash.sha256(new_checksum);
//        new_checksum = new_checksum.slice(0, 4);
//        if (checksum.toString() !== new_checksum.toString())
//            throw new Error('Invalid WIF key (checksum miss-match)')
//
//        private_key = private_key.slice(1);
//return PrivateKey.fromBuffer(private_key);

        //checking wif version
        $base58 = new Base58();
        $wifBuffer = new ByteBuffer();
        $wifBuffer->write($base58->decode($privateWif));
        $version = $wifBuffer->readInt8(0);
        if ($version !== 128) {
            //        assert.equal(0x80, version, `Expected version ${0x80}, instead got ${version}`);
            throw new \Exception('Expected version 128, instead got ' . $version);
        }

        //checking WIF checksum
        $private_key = $wifBuffer->read(0, $wifBuffer->length() - 4);
        $checksum = $wifBuffer->read($wifBuffer->length() - 4, 4);
        $new_checksum = hash('sha256', $private_key, true);
        $new_checksum = hash('sha256', $new_checksum, true);
        $new_checksum = substr($new_checksum, 0, 4);
        if ($new_checksum !== $checksum) {
            throw new \Exception('Invalid WIF key (checksum miss-match)');
        }

        //getting private_key
//        $private_key = substr(strrev($wifBuffer->read(0, $wifBuffer->length())), 1, -4);
        $private_key = substr($private_key, 1);
//        if (32 !== buf.length) {
//            console.log(`WARN: Expecting 32 bytes, instead got ${buf.length}, stack trace:`, new Error().stack);
//        }
        $length = strlen($private_key);
        if ($length !== 32) {
            throw new \Exception('Expecting 32 bytes for private_key, instead got ' . $length);
        }

        return $private_key;
    }
1336371
public static function decrypt($ciphertext, PrivateKey $rsaPrivateKey)
    {
        $split = explode(self::SEPARATOR, $ciphertext);
        if (\count($split) !== 4) {
            throw new InvalidCiphertextException('Invalid ciphertext message');
        }
        if (!\hash_equals($split[0], self::VERSION_TAG)) {
            throw new InvalidCiphertextException('Invalid version tag');
        }
        $checksum = \substr(
            \hash('sha256', implode('$', array_slice($split, 0, 3))),
            0,
            16
        );
        if (!\hash_equals($split[3], $checksum)) {
            throw new InvalidChecksumException('Invalid checksum');
        }

        $rsaCipher = Base64::decode($split[1]);
        $rsaPlain = self::rsaDecrypt(
            $rsaCipher,
            $rsaPrivateKey
        );
        $symmetricKey = hash_hmac(
            'sha256',
            $rsaCipher,
            $rsaPlain,
            true
        );

        $key = self::defuseKey($symmetricKey);
        return Crypto::decrypt(
            Base64::decode($split[2]),
            $key,
            true
        );
    }
572447
public static PrivateKey loadPrivateKey(File privateKeyFile) throws InvalidKeySpecException, IOException {
        if ( StringUtils.lowerCase(privateKeyFile.getAbsolutePath()).endsWith(".pem") ) {
            InputStream is = new FileInputStream(privateKeyFile);
            try {
                return PEM.readPrivateKey(is);
            } finally {
                try {is.close();} catch(IOException ignore) {}
            }
        } else if ( StringUtils.lowerCase(privateKeyFile.getAbsolutePath()).endsWith(".der") ) {
            InputStream is = new FileInputStream(privateKeyFile);
            try {
                return RSA.privateKeyFromPKCS8(IOUtils.toByteArray(is));
            } finally {
                try {is.close();} catch(IOException ignore) {}
            }
        } else {
            throw new AmazonClientException("Unsupported file type for private key");
        }
    }
1261400
public function importPrivateKey($exportedPrivateKey, $password = '')
    {
        try {
            $privateKeyDerEncoded = $this->cryptoService->decryptPrivateKey($exportedPrivateKey, $password);
            $receiverID = $this->calculateFingerprint(
                $this->cryptoService->extractPublicKey($privateKeyDerEncoded, '')
            );

            return new VirgilPrivateKey($receiverID, $privateKeyDerEncoded);
        } catch (Exception $exception) {
            throw new VirgilCryptoException($exception->getMessage());
        }
    }
1355040
private PrivateKey getPemPrivateKey(final String keyString) throws EncryptionException {
      try {
         final String privKeyPEM = keyString.replace("-----BEGIN PRIVATE KEY-----", "").replace("-----END PRIVATE KEY-----", "").replaceAll("\\v", "");

         final Base64 b64 = new Base64();
         final byte[] decoded = b64.decode(privKeyPEM);

         final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);
         final KeyFactory kf = KeyFactory.getInstance(ALGORITHM);

         return kf.generatePrivate(spec);
      } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
         throw new EncryptionException("Unable to obtain private key: ", e);
      }
   }
806749
public static KeyPair newKeyPair(final PublicKey publicKey, final PrivateKey privateKey)
	{
		final KeyPair keyPair = new KeyPair(publicKey, privateKey);
		return keyPair;
	}