Created
January 10, 2016 17:29
-
-
Save zukka77/44574f1505f72836efb8 to your computer and use it in GitHub Desktop.
Custom SSLSocketFactory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.FileNotFoundException; | |
import java.io.IOException; | |
import java.security.KeyManagementException; | |
import java.security.KeyStore; | |
import java.security.KeyStoreException; | |
import java.security.NoSuchAlgorithmException; | |
import java.security.SecureRandom; | |
import java.security.UnrecoverableKeyException; | |
import java.security.cert.CertificateException; | |
import javax.net.ssl.KeyManagerFactory; | |
import javax.net.ssl.SSLContext; | |
import javax.net.ssl.SSLSocketFactory; | |
import javax.net.ssl.TrustManagerFactory; | |
/** | |
* | |
* @author andrea | |
*/ | |
public class CustomSSLSocketFactory { | |
KeyStore readKeyStore() throws FileNotFoundException, IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException { | |
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); | |
// get user password and file input stream | |
String password = "keyStorePasword"; | |
java.io.FileInputStream fis = null; | |
try { | |
fis = new java.io.FileInputStream("keyStoreName"); | |
ks.load(fis, password.toCharArray()); | |
} finally { | |
if (fis != null) { | |
fis.close(); | |
} | |
} | |
return ks; | |
} | |
public SSLSocketFactory getCustomSSLSocketFactory() throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException, IOException, FileNotFoundException, CertificateException { | |
KeyStore keyStore = readKeyStore(); //your method to obtain KeyStore | |
SSLContext sslContext = SSLContext.getInstance("SSL"); | |
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); | |
trustManagerFactory.init(keyStore); | |
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); | |
keyManagerFactory.init(keyStore, "keystore_pass".toCharArray()); | |
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom()); | |
return sslContext.getSocketFactory(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment