Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save chlegou/b59298774b54bf1dc0321aceb3a00735 to your computer and use it in GitHub Desktop.
Save chlegou/b59298774b54bf1dc0321aceb3a00735 to your computer and use it in GitHub Desktop.
Here is my solution (java 1.6) removing TLS_DHE_ ciphers completely
package com.vht.sms.content.util;
import java.io.*;
import java.net.*;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import org.apache.log4j.Logger;
/**
* Here is my solution (java 1.6) removing TLS_DHE_ ciphers completely
* http://stackoverflow.com/a/18254095/359776
*/
public class SSLExcludeCipherConnectionHelper {
private Logger logger = Logger.getLogger(SSLExcludeCipherConnectionHelper.class);
private String[] exludedCipherSuites = {"_DHE_","_DH_"};
private String trustCert = null;
private TrustManagerFactory tmf;
public void setExludedCipherSuites(String[] exludedCipherSuites) {
this.exludedCipherSuites = exludedCipherSuites;
}
public SSLExcludeCipherConnectionHelper(String trustCert) {
super();
this.trustCert = trustCert;
//Security.addProvider(new BouncyCastleProvider());
try {
this.initTrustManager();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void initTrustManager() throws Exception {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = new BufferedInputStream(new FileInputStream(trustCert));
Certificate ca = null;
try {
ca = cf.generateCertificate(caInput);
logger.debug("ca=" + ((X509Certificate) ca).getSubjectDN());
} finally {
caInput.close();
}
// Create a KeyStore containing our trusted CAs
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
}
public String get(URL url) throws Exception {
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
SSLParameters params = context.getSupportedSSLParameters();
List<String> enabledCiphers = new ArrayList<String>();
for (String cipher : params.getCipherSuites()) {
boolean exclude = false;
if (exludedCipherSuites != null) {
for (int i=0; i<exludedCipherSuites.length && !exclude; i++) {
exclude = cipher.indexOf(exludedCipherSuites[i]) >= 0;
}
}
if (!exclude) {
enabledCiphers.add(cipher);
}
}
String[] cArray = new String[enabledCiphers.size()];
enabledCiphers.toArray(cArray);
// Tell the URLConnection to use a SocketFactory from our SSLContext
HttpsURLConnection urlConnection =
(HttpsURLConnection)url.openConnection();
SSLSocketFactory sf = context.getSocketFactory();
sf = new DOSSLSocketFactory(sf, cArray);
//urlConnection.setRequestMethod("POST");
urlConnection.setSSLSocketFactory(sf);
//urlConnection.setDoOutput(true);
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
StringBuffer buffer = new StringBuffer();
while ((inputLine = in.readLine()) != null)
buffer.append(inputLine);
in.close();
return buffer.toString();
}
public String post(URL url, String strBuilder) throws Exception {
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
SSLParameters params = context.getSupportedSSLParameters();
List<String> enabledCiphers = new ArrayList<String>();
for (String cipher : params.getCipherSuites()) {
boolean exclude = false;
if (exludedCipherSuites != null) {
for (int i=0; i<exludedCipherSuites.length && !exclude; i++) {
exclude = cipher.indexOf(exludedCipherSuites[i]) >= 0;
}
}
if (!exclude) {
enabledCiphers.add(cipher);
}
}
String[] cArray = new String[enabledCiphers.size()];
enabledCiphers.toArray(cArray);
// Tell the URLConnection to use a SocketFactory from our SSLContext
HttpsURLConnection urlConnection =
(HttpsURLConnection)url.openConnection();
SSLSocketFactory sf = context.getSocketFactory();
sf = new DOSSLSocketFactory(sf, cArray);
urlConnection.setSSLSocketFactory(sf);
// 3. Specify POST method
urlConnection.setRequestMethod("POST");
// 4. Set the headers
//conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//conn.setRequestProperty("Authorization", "Basic "+apiKey);
urlConnection.setDoOutput(true);
// 5. Add JSON data into POST request body
// 5.2 Get connection output stream
DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
// 5.3 Copy Content "JSON" into
wr.write(strBuilder.getBytes());
// 5.4 Send the request
wr.flush();
// 5.5 close
wr.close();
// 6. Get the response
int responseCode = urlConnection.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Request Data : " + strBuilder);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 7. Print result
//System.out.println(response.toString());
return response.toString();
}
private class DOSSLSocketFactory extends javax.net.ssl.SSLSocketFactory {
private SSLSocketFactory sf = null;
private String[] enabledCiphers = null;
private DOSSLSocketFactory(SSLSocketFactory sf, String[] enabledCiphers) {
super();
this.sf = sf;
this.enabledCiphers = enabledCiphers;
}
private Socket getSocketWithEnabledCiphers(Socket socket) {
if (enabledCiphers != null && socket != null && socket instanceof SSLSocket)
((SSLSocket)socket).setEnabledCipherSuites(enabledCiphers);
return socket;
}
@Override
public Socket createSocket(Socket s, String host, int port,
boolean autoClose) throws IOException {
return getSocketWithEnabledCiphers(sf.createSocket(s, host, port, autoClose));
}
@Override
public String[] getDefaultCipherSuites() {
return sf.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
if (enabledCiphers == null)
return sf.getSupportedCipherSuites();
else
return enabledCiphers;
}
@Override
public Socket createSocket(String host, int port) throws IOException,
UnknownHostException {
return getSocketWithEnabledCiphers(sf.createSocket(host, port));
}
@Override
public Socket createSocket(InetAddress address, int port)
throws IOException {
return getSocketWithEnabledCiphers(sf.createSocket(address, port));
}
@Override
public Socket createSocket(String host, int port, InetAddress localAddress,
int localPort) throws IOException, UnknownHostException {
return getSocketWithEnabledCiphers(sf.createSocket(host, port, localAddress, localPort));
}
@Override
public Socket createSocket(InetAddress address, int port,
InetAddress localaddress, int localport) throws IOException {
return getSocketWithEnabledCiphers(sf.createSocket(address, port, localaddress, localport));
}
/**
* “SocketException: Unconnected sockets not implemented” with self-signed SSL certificate
*/
@Override
public Socket createSocket() throws IOException {
return getSocketWithEnabledCiphers(sf.createSocket());
//throw new SocketException("Unconnected sockets not implemented");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment