从KeyStore获取私钥
@param location
@param alias
@param storeType
@param storePass
@param keyPass
@return
343581
public static PrivateKey loadPrivateKeyFromKeyStore(String location,String alias,String storeType,String storePass,String keyPass){
        try {			
        	storeType = null == storeType ? KeyStore.getDefaultType() : storeType;
        	keyPass = keyPass == null ? storePass : keyPass;
        	KeyStore keyStore = KeyStore.getInstance(storeType);
        	InputStream is = new FileInputStream(location);
        	keyStore.load(is, storePass.toCharArray());
        	// 由密钥库获取密钥的两种方式
        	return (PrivateKey) keyStore.getKey(alias, keyPass.toCharArray());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
    }
953993
public KeyStore getJavaKeyStore(String keyStoreName) throws Exception {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "getJavaKeyStore: " + keyStoreName);

        if (keyStoreName == null || keyStoreName.trim().isEmpty()) {
            throw new SSLException("No keystore name provided.");
        }

        KeyStore javaKeyStore = null;
        WSKeyStore ks = keyStoreMap.get(keyStoreName);
        if (ks != null) {
            javaKeyStore = ks.getKeyStore(false, false);
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.exit(tc, "getJavaKeyStore: " + javaKeyStore);
        return javaKeyStore;
    }
214331
public Enumeration<String> aliases() throws KeyStoreException, KeyException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "aliases");
        Enumeration<String> aliases = null;
        try {
            KeyStore jKeyStore = getKeyStore(false, false);
            if (jKeyStore == null) {
                throw new KeyStoreException("The keystore [" + name + "] is not present in the configuration");
            }
            aliases = jKeyStore.aliases();
        } catch (KeyStoreException e) {
            throw e;
        } catch (Exception ex) {
            throw new KeyException(ex.getMessage(), ex);
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.exit(tc, "aliases: " + aliases);
        return aliases;
    }
333806
public CredentialStore buildCredentialStore(Map<String, Object> parameters) {
    String ks_type = EncryptionConfigParser.getKeystoreType(parameters);
    String ks_path = EncryptionConfigParser.getKeystorePath(parameters);
    String ks_password = EncryptionConfigParser.getKeystorePassword(parameters);

    try {
      switch (ks_type) {
        // TODO this is yet another example of building a broad type (CredentialStore) based on a human-readable name
        // (json) with a bag of parameters. Need to pull out into its own pattern!
        case JCEKSKeystoreCredentialStore.TAG:
          return new JCEKSKeystoreCredentialStore(ks_path, ks_password);
        case JsonCredentialStore.TAG:
          return new JsonCredentialStore(ks_path, buildKeyToStringCodec(parameters));
        default:
          return null;
      }
    } catch (IOException e) {
      log.error("Error building credential store, returning null", e);
      return null;
    }
  }
588751
public KeyStore getKeyStore(boolean reinitialize, boolean createIfNotPresent) throws Exception {
        if (myKeyStore == null || reinitialize) {
            myKeyStore = do_getKeyStore(reinitialize, createIfNotPresent);
        }

        return myKeyStore;
    }
896910
protected PrivateKey getKey(KeyStore ks, String alias, char[] password) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
      return CertificateHelper.getKey(ks, alias, password);
   }
1181556
public String getKeyStore()
			throws IOException
	{
		if (!isSecured())
		{
			return null;
		}
		
		if (keyStore == null)
		{
			throw new IllegalArgumentException("You must specify keystore file location");
		}

		final File keyStoreFile = new File(keyStore);

		if (!keyStoreFile.exists())
		{
			throw new FileNotFoundException(String.format("KeyStore file '%s' does not exists",
														  keyStoreFile.getAbsolutePath()));
		}

		return keyStore;
	}
1189627
public PrivateKey get(KeyStoreChooser keyStoreChooser, PrivateKeyChooserByAlias privateKeyChooserByAlias) {
        CacheKey cacheKey = new CacheKey(keyStoreChooser.getKeyStoreName(), privateKeyChooserByAlias.getAlias());
        PrivateKey retrievedPrivateKey = cache.get(cacheKey);

        if (retrievedPrivateKey != null) {
            return retrievedPrivateKey;
        }

        KeyStore keyStore = keyStoreRegistry.get(keyStoreChooser);

        if (keyStore != null) {
            PrivateKeyFactoryBean factory = new PrivateKeyFactoryBean();
            factory.setKeystore(keyStore);
            factory.setAlias(privateKeyChooserByAlias.getAlias());
            factory.setPassword(privateKeyChooserByAlias.getPassword());
            try {
                factory.afterPropertiesSet();
                PrivateKey privateKey = (PrivateKey) factory.getObject();

                if (privateKey != null) {
                    cache.put(cacheKey, privateKey);
                }
                return privateKey;
            } catch (Exception e) {
                throw new PrivateKeyException("error initializing private key factory bean", e);
            }
        }

        return null;
    }
78975
public boolean isKeyEntry(String alias) throws KeyStoreException, KeyException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "isKeyEntry: " + alias);
        boolean isKey = false;
        try {
            KeyStore jKeyStore = getKeyStore(false, false);
            if (jKeyStore == null) {
                throw new KeyStoreException("The keystore [" + name + "] is not present in the configuration");
            }
            isKey = jKeyStore.isKeyEntry(alias);
        } catch (KeyStoreException e) {
            throw e;
        } catch (Exception ex) {
            throw new KeyException(ex.getMessage(), ex);
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.exit(tc, "isKeyEntry: " + isKey);
        return isKey;
    }
694570
public static Authenticator buildAuthenticatorWithJwk(final String location) {
        if (location != null && isUrl(location)) {
            return new JwksAuthenticator(location);
        }
        return null;
    }
873131
public void setCertificateEntry(String alias, Certificate cert) throws KeyStoreException, KeyException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(this, tc, "setCertificateEntry", new Object[] { alias, cert });
        }
        if (Boolean.parseBoolean(getProperty(Constants.SSLPROP_KEY_STORE_READ_ONLY))) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(this, tc, "Unable to update readonly store");
            }
            throw new KeyStoreException("Unable to add to read-only store");
        }
        final KeyStoreManager mgr = KeyStoreManager.getInstance();

        try {
            KeyStore jKeyStore = getKeyStore(false, false);
            if (null == jKeyStore) {
                final String keyStoreLocation = getProperty(Constants.SSLPROP_KEY_STORE);
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Cannot load the Java keystore at location \"" + keyStoreLocation + "\"");
                }
                throw new KeyStoreException("Cannot load the Java keystore at location \"" + keyStoreLocation + "\"");
            }

            // store the cert... errors are thrown if conflicts or errors occur
            jKeyStore.setCertificateEntry(alias, cert);

            try {
                store();
            } catch (IOException e) {
                // Note: debug + ffdc in store() itself

                // on z/OS we have an issue where the certificate may be stored but the
                // alias
                // already exists in RACF so the keystore API will through an
                // IOException
                // we need to catch this condition on z/OS and if the certs is in the
                // keystore
                // prior after adding the certificate then we know the cert was actually
                // added and its not
                // a true failure. If the cert was not added then we need to rethrow the
                // exception.
                final String ksType = getProperty(Constants.SSLPROP_KEY_STORE_TYPE);
                if ((ksType.equals(Constants.KEYSTORE_TYPE_JCERACFKS) || ksType.equals(Constants.KEYSTORE_TYPE_JCECCARACFKS)
                     || ksType.equals(Constants.KEYSTORE_TYPE_JCEHYBRIDRACFKS))) {
                    KeyStore ks = getKeyStore(true, false);

                    if (mgr.checkIfSignerAlreadyExistsInTrustStore((X509Certificate) cert, ks)) {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "Certificate already exists in RACF: " + e.getMessage());
                        }
                    } else {
                        throw new KeyException(e.getMessage(), e);
                    }
                } else {
                    throw new KeyException(e.getMessage(), e);
                }
            }
        } catch (KeyStoreException kse) {
            throw kse;
        } catch (KeyException ke) {
            throw ke;
        } catch (Exception e) {
            throw new KeyException(e.getMessage(), e);
        }

        // after adding the certificate, clear the keystore and SSL caches so it
        // reloads it.
        AbstractJSSEProvider.clearSSLContextCache();
        mgr.clearJavaKeyStoresFromKeyStoreMap();

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(this, tc, "setCertificateEntry");
        }
    }
1003177
protected String resolveKey(String alias) {
		List<String> possibleKeys = aliases.get(alias);
		for (String key : possibleKeys) {
			if (resolver.containsProperty(key)) {
				return key;
			}
		}
		return null;
	}
184299
private static KeyStore saveCertificateAsKeyStore(KeyStore existingKeyStore, boolean deleteOnExit, String keyStoreFileName, String certificationAlias, Key privateKey, char[] keyStorePassword, Certificate[] chain, X509Certificate caCert) {
        try {
            KeyStore keyStore = existingKeyStore;
            if (keyStore == null) {
                // create new key store
                keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
                keyStore.load(null, keyStorePassword);
            }

            // add certificate
            try {
                keyStore.deleteEntry(certificationAlias);
            } catch (KeyStoreException kse) {
                // ignore as may not exist in keystore yet
            }
            keyStore.setKeyEntry(certificationAlias, privateKey, keyStorePassword, chain);

            // add CA certificate
            try {
                keyStore.deleteEntry(KEY_STORE_CA_ALIAS);
            } catch (KeyStoreException kse) {
                // ignore as may not exist in keystore yet
            }
            keyStore.setCertificateEntry(KEY_STORE_CA_ALIAS, caCert);

            // save as JKS file
            String keyStoreFileAbsolutePath = new File(keyStoreFileName).getAbsolutePath();
            try (FileOutputStream fileOutputStream = new FileOutputStream(keyStoreFileAbsolutePath)) {
                keyStore.store(fileOutputStream, keyStorePassword);
                MOCK_SERVER_LOGGER.trace("Saving key store to file [" + keyStoreFileAbsolutePath + "]");
            }
            if (deleteOnExit) {
                new File(keyStoreFileAbsolutePath).deleteOnExit();
            }
            return keyStore;
        } catch (Exception e) {
            throw new RuntimeException("Exception while saving KeyStore", e);
        }
    }
504869
private static TrustManagerFactory getTrustManagerFactory(InputStream trustStoreStream, StoreProperties storeProperties)
      throws IOException, GeneralSecurityException {

    // use provider if given, otherwise use the first matching security provider
    final KeyStore ks;
    if (StringUtils.isNotBlank(storeProperties.getProvider())) {
      ks = KeyStore.getInstance(storeProperties.getType(), storeProperties.getProvider());
    }
    else {
      ks = KeyStore.getInstance(storeProperties.getType());
    }

    ks.load(trustStoreStream, storeProperties.getPassword().toCharArray());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(storeProperties.getManagerType());
    tmf.init(ks);
    return tmf;
  }
631845
public String validate(KeyStore keyStore, String keyAlias) throws CertificateException {
        String result = null;
        if (keyAlias != null) {
            try {
                validate(keyStore, keyStore.getCertificate(keyAlias));
            } catch (KeyStoreException kse) {
                logger.debug("", kse);
                throw new CertificateException("Unable to validate certificate" +
                        " for alias [" + keyAlias + "]: " + kse.getMessage(), kse);
            }
            result = keyAlias;
        }
	return result;
    }
415916
public TLSBuilder withTrustStore(final String trustStoreType, final InputStream trustStoreStream, final char[] trustStorePassword)
    {
        return withKeyStore(trustStoreType, trustStoreStream, trustStorePassword);
    }
1294083
public static void addTrustedCertificate(String alias, X509Certificate cert, File storeFile, String storePassword) {
        try {
            KeyStore store = openKeyStore(storeFile, storePassword);
            store.setCertificateEntry(alias, cert);
            saveKeyStore(storeFile, store, storePassword);
        } catch (Exception e) {
            throw new RuntimeException("Failed to import certificate into trust store " + storeFile, e);
        }
    }