Resolve the password from the given private key file. If no password is set an empty Optional
will be returned.

@param privateKeyFile
the private key file
@param processor
the processor
@return the optional
171656
public static Optional<String> resolvePassword(File privateKeyFile,
		@NonNull BruteForceProcessor processor)
	{
		Optional<String> optionalPassword = Optional.empty();
		try
		{
			boolean isPasswordProtected = PrivateKeyReader
				.isPrivateKeyPasswordProtected(privateKeyFile);

			if (!isPasswordProtected)
			{


				String attempt;
				attempt = processor.getCurrentAttempt();
				Security.addProvider(new BouncyCastleProvider());
				while (true)
				{
					try
					{
						EncryptedPrivateKeyReader.getKeyPair(privateKeyFile, attempt);
						optionalPassword = Optional.of(attempt);
						break;
					}
					catch (IOException e)
					{
						attempt = processor.getCurrentAttempt();
						processor.increment();
					}
				}
			}
		}
		catch (IOException ex)
		{
			return optionalPassword;
		}
		return optionalPassword;
	}
246434
public static PrivateKey generatePrivateKey(String algorithm, KeySpec keySpec) {
		if (null == keySpec) {
			return null;
		}
		algorithm = getAlgorithmAfterWith(algorithm);
		try {
			return getKeyFactory(algorithm).generatePrivate(keySpec);
		} catch (Exception e) {
			throw new CryptoException(e);
		}
	}
1077935
protected String getPrivateKey() throws Exception {
        String location = this.properties.getProperty(SECRET_LOCATION);
        if (StringUtils.isBlank(location)) {
            throw new DatabaseEngineException("Encryption was specified but there's no location specified for the private key.");
        }

        File f = new File(location);
        if (!f.canRead()) {
            throw new DatabaseEngineException("Specified file '" + location + "' does not exist or the application does not have read permissions over it.");
        }

        return readString(new FileInputStream(f)).trim();
    }
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();
    	}
    }
413160
public static SslContextBuilder forServer(
      File keyCertChainFile, File keyFile, String keyPassword) {
    return configure(SslContextBuilder.forServer(keyCertChainFile, keyFile, keyPassword));
  }
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);
      }
   }
1357223
public static PrivateKey getPrivateKey(KeyStore keyStore, String alias, String keyPass)
      throws GeneralSecurityException {
    return (PrivateKey) keyStore.getKey(alias, keyPass.toCharArray());
  }
560537
public PrivateKey getPrivateKey(String alias, String password) {
        Key key = getKey(alias, password);
        if (key instanceof PrivateKey) {
            return (PrivateKey) key;
        } else {
            throw new IllegalStateException(format("Key with alias '%s' was not a private key, but was: %s",
                    alias, key.getClass().getSimpleName()));
        }
    }
614197
private KeyStore convertPemFileToKeyStore(Path pemFile) {
		String pem;
		try {
			pem = FileUtils.readFileToString(pemFile.toFile(), StandardCharsets.US_ASCII);
		} catch (IOException e) {
			logger.warn("Failed to read .pem file:", e);
			JOptionPane.showMessageDialog(
					this,
					Constant.messages.getString("dynssl.importpem.failedreadfile", e.getLocalizedMessage()),
					Constant.messages.getString("dynssl.importpem.failed.title"),
					JOptionPane.ERROR_MESSAGE);
			return null;
		}

		byte[] cert;
		try {
			cert = SslCertificateUtils.extractCertificate(pem);
			if (cert.length == 0) {
				JOptionPane.showMessageDialog(
						this,
						Constant.messages.getString(
								"dynssl.importpem.nocertsection",
								SslCertificateUtils.BEGIN_CERTIFICATE_TOKEN,
								SslCertificateUtils.END_CERTIFICATE_TOKEN),
						Constant.messages.getString("dynssl.importpem.failed.title"),
						JOptionPane.ERROR_MESSAGE);
				return null;
			}
		} catch (IllegalArgumentException e) {
			logger.warn("Failed to base64 decode the certificate from .pem file:", e);
			JOptionPane.showMessageDialog(
					this,
					Constant.messages.getString("dynssl.importpem.certnobase64"),
					Constant.messages.getString("dynssl.importpem.failed.title"),
					JOptionPane.ERROR_MESSAGE);
			return null;
		}

		byte[] key;
		try {
			key = SslCertificateUtils.extractPrivateKey(pem);
			if (key.length == 0) {
				JOptionPane.showMessageDialog(
						this,
						Constant.messages.getString(
								"dynssl.importpem.noprivkeysection",
								SslCertificateUtils.BEGIN_PRIVATE_KEY_TOKEN,
								SslCertificateUtils.END_PRIVATE_KEY_TOKEN),
						Constant.messages.getString("dynssl.importpem.failed.title"),
						JOptionPane.ERROR_MESSAGE);
				return null;
			}
		} catch (IllegalArgumentException e) {
			logger.warn("Failed to base64 decode the private key from .pem file:", e);
			JOptionPane.showMessageDialog(
					this,
					Constant.messages.getString("dynssl.importpem.privkeynobase64"),
					Constant.messages.getString("dynssl.importpem.failed.title"),
					JOptionPane.ERROR_MESSAGE);
			return null;
		}

		try {
			return SslCertificateUtils.pem2KeyStore(cert, key);
		} catch (Exception e) {
			logger.error("Error creating KeyStore for Root CA cert from .pem file:", e);
			JOptionPane.showMessageDialog(
					this,
					Constant.messages.getString("dynssl.importpem.failedkeystore", e.getLocalizedMessage()),
					Constant.messages.getString("dynssl.importpem.failed.title"),
					JOptionPane.ERROR_MESSAGE);
			return null;
		}
	}
659114
def load_pem_private_key(data, password):
    """"""
    key = _serialization.load_pem_private_key(
        data, password, _backends.default_backend())
    return key
1092897
public byte[] sign(String privateKeyId, byte[] message) {
		Signer signer = cache.get(privateKeyId);

		if (signer != null) {
			return signer.sign(message);
		}

		SignerImpl signerImpl = new SignerImpl();
		PrivateKey privateKey = privateKeyMap.get(privateKeyId);

		if (privateKey == null) {
			throw new SignatureException("private key not found: privateKeyId=" + privateKeyId);
		}

		signerImpl.setPrivateKey(privateKey);
		signerImpl.setAlgorithm(algorithm);
		signerImpl.setProvider(provider);
		cache.put(privateKeyId, signerImpl);
		return signerImpl.sign(message);
	}
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;
    }
669392
static public void genCertificateRequest(String dname,
                                             String emailAddressOfCA,
                                             String password,
                                             File keyFile,
                                             File certFile,
                                             File certReqFile)
        throws Exception {

        String sigAlgName = "MD5WithRSA";
        String keyAlgName = "RSA";

	CertUtil.init();

	X509Name name = new X509Name(dname);

	String certSubject = X509NameHelper.toString(name);

	System.out.println("Generating a 1024 bit RSA private key");

        // Generate a new key pair.
        KeyPairGenerator keygen = KeyPairGenerator.getInstance(keyAlgName);
	keygen.initialize(1024);
        KeyPair keyPair = keygen.genKeyPair();
        PrivateKey privKey = keyPair.getPrivate();
        PublicKey pubKey = keyPair.getPublic();

        // Generate the certificate request.
        DERSet derSet = new DERSet();
        PKCS10CertificationRequest request =
            new PKCS10CertificationRequest(
                sigAlgName,
                name,
                pubKey,
                derSet,
                privKey);

        // Save the certificate request to a .pem file.
        byte[] data = request.getEncoded();
	byte[] encodedData = Base64.encode(data);

        PrintStream ps = null;

	try {
	    ps = new PrintStream(new FileOutputStream(certReqFile));

            boolean caEmail = false;

            if ((emailAddressOfCA != null) &&
                (emailAddressOfCA.length() > 0)) {
                caEmail = true;
                ps.print("\n\n" + "Please mail the following certificate request to " + emailAddressOfCA);
            } else {
                ps.print("\n\n" + "Please send the following certificate request to the Certificate Authority (CA). Refer to CA instructions for details on to send the request.");
            }
            ps.print("\n\n"
                     + "==================================================================\n"
                     + "\n"
                     + "Certificate Subject:\n"
                     + "\n"
                     + certSubject
                     + "\n"
                     + "\n"
                     + "The above string is known as your user certificate subject, and it \n"
                     + "uniquely identifies this user.\n"
                     + "\n"
                     + "To install this user certificate, please save this e-mail message\n"
                     + "into the following file.\n"
                     + "\n"
                     + "\n"
                     + certReqFile.getAbsolutePath()
                     + "\n"
                     + "\n"
                     + "\n"
                     + "      You need not edit this message in any way. Simply \n"
                     + "      save this e-mail message to the file.\n"
                     + "\n"
                     + "\n"
                     + "If you have any questions about the certificate contact\n"
                     + "the Certificate Authority");
            if (caEmail) {
                ps.print("at " + emailAddressOfCA);
            }
            ps.print("\n\n");
	    PEMUtils.writeBase64(ps,
				 "-----BEGIN CERTIFICATE REQUEST-----",
				 encodedData,
				 "-----END CERTIFICATE REQUEST-----");
	} finally {
	    if (ps != null) {
		ps.close();
	    }
	}

        // Save private key to a .pem file.
        OpenSSLKey key = new BouncyCastleOpenSSLKey(privKey);
        if (password != null) {
            key.encrypt(password);
        }
	// this will set the permissions correctly already
        key.writeTo(keyFile.getAbsolutePath());

        // Create an empty cert file.
        certFile.createNewFile();

	System.out.println("A private key and a certificate request has been generated with the subject:");
	System.out.println();
	System.out.println(certSubject);
	System.out.println();

	System.out.println("The private key is stored in " +
			   keyFile.getAbsolutePath());
	System.out.println("The request is stored in " +
			   certReqFile.getAbsolutePath());

    }
203427
public static boolean checkPassPhrase(File keyFilePath, String passPhrase) {
        KeyPair key = parsePrivateKeyFile(keyFilePath);
        boolean isValidPhrase = passPhrase != null && !passPhrase.trim().isEmpty();
        if (key == null) {
            return false;
        } else if (key.isEncrypted() != isValidPhrase) {
            return false;
        } else if (key.isEncrypted()) {
            return key.decrypt(passPhrase);
        }
        return true;
    }
934252
def load_pem(cls, private_key, password=None):
        
        # TODO(sam): try to break this in tests
        maybe_path = normpath(private_key)
        if os.path.isfile(maybe_path):
            with open(maybe_path, 'rb') as pkf:
                private_key = pkf.read()
        if not isinstance(private_key, six.binary_type):
            private_key = private_key.encode('utf-8')

        pkey = serialization.load_pem_private_key(
            private_key,
            password=password,
            backend=crypto_backends.default_backend())
        return cls(pkey)
706667
private static KeyPair parsePrivateKeyFile(File keyFile) {
        if (keyFile == null) {
          return null;
        }

        try {
            JSch jsch = new JSch();
            KeyPair key = KeyPair.load(jsch, keyFile.getAbsolutePath());
            return key;
        } catch (JSchException ex) {
            return null;
        }
    }
264251
public final PrivateKey lazyGetOurPrivateKey() throws Exception {
    if (this.ourPrivateKey == null && lazyGetKeystore() != null) {
      KeyStore.ProtectionParameter protParam = new KeyStore.
        PasswordProtection(this.ksPassword);
      KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry)
        this.keyStore.getEntry("AJettyFileExch" + this.ajettyIn, protParam);
      this.ourPrivateKey = pkEntry.getPrivateKey();
    }
    return this.ourPrivateKey;
  }