Get the RSA private key value.

@param provider
the Java security provider.
@return the RSA private key value
501231
private PrivateKey getRSAPrivateKey(Provider provider) {

        try {
            RSAPrivateKeySpec privateKeySpec = getRSAPrivateKeySpec();
            KeyFactory factory = provider != null ? KeyFactory.getInstance("RSA", provider)
                    : KeyFactory.getInstance("RSA");

            return factory.generatePrivate(privateKeySpec);
        } catch (GeneralSecurityException e) {
            throw new IllegalStateException(e);
        }
    }
1017418
public PrivateKey getPrivateKey_PKCS8Encoded(byte[] keyBytes){  
        try {
            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);  
            KeyFactory keyFactory = KeyFactory.getInstance(algorithm);  
            return keyFactory.generatePrivate(spec); 
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		} 
    	return null;
    }
240344
public static EncryptionProvider getProvider(final Key key) throws UnsupportedAlgorithmException, UnsupportedKeySizeException {

		String algorithm = key.getAlgorithm();

		SupportedKeyGenAlgorithms keyAlgorithm = getAlgorithm(algorithm);

		switch (keyAlgorithm) {
		case AES:
			return new AESEncryptionProvider(key);
			
		case DES:
			return new DESEdeEncryptionProvider(key);
			
		default:
			throw new UnsupportedAlgorithmException("Algorithm [" + keyAlgorithm + "] is not supported.");
		}

	}
1053575
public KeyPair getKeyPair() throws GeneralSecurityException, IOException {
        if (privateKeyAsSeed == null) {
            throw new IllegalStateException("Public-only NKey");
        }

        DecodedSeed decoded = decodeSeed(privateKeyAsSeed);
        byte[] seedBytes = new byte[ED25519_SEED_SIZE];
        byte[] pubBytes = new byte[ED25519_PUBLIC_KEYSIZE];

        System.arraycopy(decoded.bytes, 0, seedBytes, 0, seedBytes.length);
        System.arraycopy(decoded.bytes, seedBytes.length, pubBytes, 0, pubBytes.length);

        EdDSAPrivateKeySpec privKeySpec = new EdDSAPrivateKeySpec(seedBytes, NKey.ed25519);
        EdDSAPrivateKey privKey = new EdDSAPrivateKey(privKeySpec);
        EdDSAPublicKeySpec pubKeySpec = new EdDSAPublicKeySpec(pubBytes, NKey.ed25519);
        EdDSAPublicKey pubKey = new EdDSAPublicKey(pubKeySpec);

        return new KeyPair(pubKey, privKey);
    }
705052
public String getPublicKey() {
        RSAPublicKey key = InstanceIdentityProvider.RSA.getPublicKey();
        if (key == null) {
            return null;
        }
        byte[] encoded = Base64.encodeBase64(key.getEncoded());
        int index = 0;
        StringBuilder buf = new StringBuilder(encoded.length + 20);
        while (index < encoded.length) {
            int len = Math.min(64, encoded.length - index);
            if (index > 0) {
                buf.append("\n");
            }
            buf.append(new String(encoded, index, len, Charsets.UTF_8));
            index += len;
        }
        return String.format("-----BEGIN PUBLIC KEY-----%n%s%n-----END PUBLIC KEY-----%n", buf.toString());
    }
1133767
public static String RSAKeyToString (PrivateKey key)
    {
        try {
            KeyFactory kf = KeyFactory.getInstance("RSA");
            RSAPrivateKeySpec spec = kf.getKeySpec(key, RSAPrivateKeySpec.class);
            StringBuilder buf = new StringBuilder();
            buf.append(spec.getModulus().toString(16))
                .append(SPLIT)
                .append(spec.getPrivateExponent().toString(16));
            return buf.toString();
        } catch (GeneralSecurityException gse) {
            log.warning("Failed to convert key to string", gse);
        }
        return null;
    }
816465
private static PrivateKey getPrivateKey(final String algorithm, final File privateKeyFile) {
		return getPrivateKeyFromBytes(algorithm, readBytes(privateKeyFile));
	}
565807
public static String privateKey2String(PrivateKey key) {
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(key.getEncoded());
        return new String(Base64.getEncoder().encode(spec.getEncoded()), StandardCharsets.UTF_8);
    }
420839
private static PrivateKey commonGetPrivatekeyByText(String keyText)
            throws NoSuchAlgorithmException, InvalidKeySpecException {
        byte[] keyBytes = Base64.base64ToByteArray(keyText);
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA);
        return keyFactory.generatePrivate(pkcs8EncodedKeySpec);
    }
974624
public static PrivateKey decodePrivateKey(String pemEncoded) throws Exception {
        pemEncoded = removeBeginEnd(pemEncoded);
        byte[] pkcs8EncodedBytes = Base64.getDecoder().decode(pemEncoded);

        // extract the private key

        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey privKey = kf.generatePrivate(keySpec);
        return privKey;
    }
642382
public byte[] calculateVrfSignature(byte[] privateKey, byte[] message) {
    if (privateKey == null || privateKey.length != 32) {
      throw new IllegalArgumentException("Invalid private key!");
    }

    byte[] random = provider.getRandom(64);
    return provider.calculateVrfSignature(random, privateKey, message);
  }
781047
public static PrivateKey generatePrivateKey(BigInteger modulus, BigInteger privateExponent) {
		return SecureUtil.generatePrivateKey(ALGORITHM_RSA.getValue(), new RSAPrivateKeySpec(modulus, privateExponent));
	}
820893
public static JsonWebKey fromRSA(KeyPair keyPair) {

        RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey) keyPair.getPrivate();
        JsonWebKey key = null;

        if (privateKey != null) {

            key = new JsonWebKey().withKty(JsonWebKeyType.RSA).withN(toByteArray(privateKey.getModulus()))
                    .withE(toByteArray(privateKey.getPublicExponent()))
                    .withD(toByteArray(privateKey.getPrivateExponent())).withP(toByteArray(privateKey.getPrimeP()))
                    .withQ(toByteArray(privateKey.getPrimeQ())).withDp(toByteArray(privateKey.getPrimeExponentP()))
                    .withDq(toByteArray(privateKey.getPrimeExponentQ()))
                    .withQi(toByteArray(privateKey.getCrtCoefficient()));
        } else {

            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

            key = new JsonWebKey().withKty(JsonWebKeyType.RSA).withN(toByteArray(publicKey.getModulus()))
                    .withE(toByteArray(publicKey.getPublicExponent())).withD(null).withP(null).withQ(null).withDp(null)
                    .withDq(null).withQi(null);
        }

        return key;
    }
1273905
private static PrivateKey getPrivateKey(String filename, String password, String key) {
        if(logger.isDebugEnabled()) logger.debug("filename = " + filename + " key = " + key);
        PrivateKey privateKey = null;

        try {
            KeyStore keystore = KeyStore.getInstance("JKS");
            keystore.load(Config.getInstance().getInputStreamFromFile(filename),
                    password.toCharArray());

            privateKey = (PrivateKey) keystore.getKey(key,
                    password.toCharArray());
        } catch (Exception e) {
            logger.error("Exception:", e);
        }

        if (privateKey == null) {
            logger.error("Failed to retrieve private key from keystore");
        }

        return privateKey;
    }
270266
@SneakyThrows
    private static Credential getEncryptionCredential(final WsFederationConfiguration config) {
        LOGGER.debug("Locating encryption credential private key [{}]", config.getEncryptionPrivateKey());
        val br = new BufferedReader(new InputStreamReader(config.getEncryptionPrivateKey().getInputStream(), StandardCharsets.UTF_8));
        Security.addProvider(new BouncyCastleProvider());
        LOGGER.debug("Parsing credential private key");
        try (val pemParser = new PEMParser(br)) {
            val privateKeyPemObject = pemParser.readObject();
            val converter = new JcaPEMKeyConverter().setProvider(new BouncyCastleProvider());

            val kp = FunctionUtils.doIf(Predicates.instanceOf(PEMEncryptedKeyPair.class),
                Unchecked.supplier(() -> {
                    LOGGER.debug("Encryption private key is an encrypted keypair");
                    val ckp = (PEMEncryptedKeyPair) privateKeyPemObject;
                    val decProv = new JcePEMDecryptorProviderBuilder().build(config.getEncryptionPrivateKeyPassword().toCharArray());
                    LOGGER.debug("Attempting to decrypt the encrypted keypair based on the provided encryption private key password");
                    return converter.getKeyPair(ckp.decryptKeyPair(decProv));
                }),
                Unchecked.supplier(() -> {
                    LOGGER.debug("Extracting a keypair from the private key");
                    return converter.getKeyPair((PEMKeyPair) privateKeyPemObject);
                }))
                .apply(privateKeyPemObject);

            val certParser = new X509CertParser();
            LOGGER.debug("Locating encryption certificate [{}]", config.getEncryptionCertificate());
            certParser.engineInit(config.getEncryptionCertificate().getInputStream());
            LOGGER.debug("Invoking certificate engine to parse the certificate [{}]", config.getEncryptionCertificate());
            val cert = (X509CertificateObject) certParser.engineRead();
            LOGGER.debug("Creating final credential based on the certificate [{}] and the private key", cert.getIssuerDN());
            return new BasicX509Credential(cert, kp.getPrivate());
        }

    }
879647
private static PublicKey getPublicKey(String modulus, String exponent) {
		try {
			BigInteger b1 = new BigInteger(modulus);
			BigInteger b2 = new BigInteger(exponent);
			KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
			RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
			return keyFactory.generatePublic(keySpec);
		} catch (Exception e) {
			LogUtil.writeErrorLog("构造RSA公钥失败：" + e);
			return null;
		}
	}
1075890
def _load_rsa_private_key(pem):
    """"""
    # ADB uses private RSA keys in pkcs#8 format. 'rsa' library doesn't support
    # them natively. Do some ASN unwrapping to extract naked RSA key
    # (in der-encoded form). See https://www.ietf.org/rfc/rfc2313.txt.
    # Also http://superuser.com/a/606266.
    try:
        der = rsa.pem.load_pem(pem, 'PRIVATE KEY')
        keyinfo, _ = decoder.decode(der)
        if keyinfo[1][0] != univ.ObjectIdentifier(
                '1.2.840.113549.1.1.1'):  # pragma: no cover
            raise ValueError('Not a DER-encoded OpenSSL private RSA key')
        private_key_der = keyinfo[2].asOctets()
    except IndexError:  # pragma: no cover
        raise ValueError('Not a DER-encoded OpenSSL private RSA key')
    return rsa.PrivateKey.load_pkcs1(private_key_der, format='DER')