Last active
August 29, 2015 14:20
-
-
Save RakeshChouhan/641dc1d47b17389cf1cc to your computer and use it in GitHub Desktop.
SSL certificate download from the https server so you dont have to manually download it through browser or keytool.
This file contains hidden or 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.File; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.net.URL; | |
import java.security.cert.Certificate; | |
import java.security.cert.CertificateException; | |
import java.security.cert.X509Certificate; | |
import javax.net.ssl.HttpsURLConnection; | |
import javax.net.ssl.SSLContext; | |
import javax.net.ssl.SSLSocketFactory; | |
import javax.net.ssl.TrustManager; | |
import javax.net.ssl.X509TrustManager; | |
/** | |
* | |
* @author chouhan_r | |
* | |
*/ | |
public class DownloadSSL | |
{ | |
private static final String SEPERATOR = System.getProperty("file.separator"); | |
public static void downloadSSLCertificate(){ | |
String httpsURL = "https://localhost:8443"; | |
if(httpsURL != null && httpsURL.contains("https")){ | |
FileOutputStream writer = null; | |
try { | |
URL myurl = new URL(httpsURL); | |
SSLContext ssl = SSLContext.getInstance("TLSv1"); | |
ssl.init(null, new TrustManager[] { new SimpleX509TrustManager() }, | |
null); | |
SSLSocketFactory factory = ssl.getSocketFactory(); | |
HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection(); | |
con.setSSLSocketFactory(factory); | |
InputStream ins = con.getInputStream(); | |
String filePath = "sslcertificate.cer"; | |
File file = new File(filePath); | |
writer = new FileOutputStream(file); | |
for (Certificate cert : con.getServerCertificates()) { | |
writer.write(cert.getEncoded()); | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
}finally{ | |
if(writer!=null){ | |
try { | |
writer.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
System.out.println("certificate downloaded"); | |
} | |
} | |
} | |
class SimpleX509TrustManager implements X509TrustManager { | |
public void checkClientTrusted( | |
X509Certificate[] cert, String s) | |
throws CertificateException { | |
} | |
public void checkServerTrusted( | |
X509Certificate[] cert, String s) | |
throws CertificateException { | |
} | |
@Override | |
public X509Certificate[] getAcceptedIssuers() { | |
// TODO Auto-generated method stub | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Download SSL certificate from the https server pragmatically. No need to download it manually like from web browser or keytool.