private KeyStore createKeyStore() { final KeyStore keyStore = createStore(this.keyStoreType); InputStream keyStoreStream = null; if (this.keyStoreSource != null) { keyStoreStream = createStoreStream(this.keyStoreSource); } try { keyStore.load(keyStoreStream, toCharArray(this.keyStorePassword)); } catch (IOException ex) { if (ex.getCause() instanceof UnrecoverableKeyException) { throw new IllegalArgumentException("Failed to load keystore. Maybe the password is not correct.", ex); } throw new IllegalStateException("Failed to load keystore. Maybe the keystore type is not correct.", ex); } catch (NoSuchAlgorithmException ex) { throw new IllegalStateException("Failed to load keystore.", ex); } catch (CertificateException ex) { throw new IllegalStateException("Failed to load keystore.", ex); } finally { Closeables.closeQuietly(keyStoreStream); } return keyStore; }
private KeyStore createTrustStore() { final KeyStore trustStore = createStore(this.trustStoreType); InputStream trustStoreStream = null; if (this.trustStoreSource != null) { trustStoreStream = createStoreStream(this.trustStoreSource); } try { trustStore.load(trustStoreStream, toCharArray(this.trustStorePassword)); } catch (IOException ex) { if (ex.getCause() instanceof UnrecoverableKeyException) { throw new IllegalArgumentException("Failed to load truststore. Maybe the password is not correct.", ex); } throw new IllegalStateException("Failed to load truststore. Maybe the truststore type is not correct.", ex); } catch (NoSuchAlgorithmException ex) { throw new IllegalStateException("Failed to load truststore.", ex); } catch (CertificateException ex) { throw new IllegalStateException("Failed to load truststore.", ex); } finally { Closeables.closeQuietly(trustStoreStream); } return trustStore; }
private KeyManager[] getKeyManagers() { // PKCS#11 provider provides the keys, source for the keystore should not be set if (this.keyStoreSource == null && this.keyStoreType != KeyStoreType.PKCS11) { return null; } else if (this.keyStoreSource != null && this.keyStoreType == KeyStoreType.PKCS11) { throw new IllegalArgumentException("The keystore type is PKCS#11, the keystore should not be set."); } final KeyManagerFactory keyManagerFactory = createKeyManagerFactory(); KeyStore keyStore = this.createKeyStore(); char[] password = toCharArray(this.keyPassword != null ? this.keyPassword : this.keyStorePassword); if (this.keyAlias != null) { // We cannot pass key alias to KeyManagerFactory to define which key should be used. Furthermore, other // keys in the keystore may have different passwords, which could cause failures while retrieving the key. keyStore = this.createRepacementKeyStore(keyStore, password); } try { keyManagerFactory.init(keyStore, password); } catch (GeneralSecurityException ex) { throw new IllegalArgumentException("Failed to init KeyManagerFactory for " + this.keyStoreSource, ex); } return keyManagerFactory.getKeyManagers(); }