io.cloudslang.content.mail.sslconfig.SSLUtils Maven / Gradle / Ivy
package io.cloudslang.content.mail.sslconfig;
import javax.net.ssl.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
/**
* Created by giloan on 11/5/2014.
*/
public class SSLUtils {
public static KeyStore createKeyStore(final URL url, final String password)
throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
if (url == null) {
throw new IllegalArgumentException("Keystore url may not be null");
}
KeyStore keystore = KeyStore.getInstance("jks");
InputStream is = null;
try {
is = url.openStream();
keystore.load(is, password != null ? password.toCharArray() : null);
} finally {
if (is != null) is.close();
}
return keystore;
}
public static KeyManager[] createKeyManagers(final KeyStore keystore, final String password)
throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
if (keystore == null) {
throw new IllegalArgumentException("Keystore may not be null");
}
KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
kmfactory.init(keystore, password != null ? password.toCharArray() : null);
return kmfactory.getKeyManagers();
}
public static TrustManager[] createAuthTrustManagers(final KeyStore keystore)
throws KeyStoreException, NoSuchAlgorithmException {
if (keystore == null) {
throw new IllegalArgumentException("Keystore may not be null");
}
TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
tmfactory.init(keystore);
TrustManager[] trustmanagers = tmfactory.getTrustManagers();
for (int i = 0; i < trustmanagers.length; i++) {
if (trustmanagers[i] instanceof X509TrustManager) {
trustmanagers[i] = new AuthSSLX509TrustManager(
(X509TrustManager) trustmanagers[i]);
}
}
return trustmanagers;
}
}