How to work-it in Tomcat 7
I wanted to support a self signed certificate in a Tomcat App but the following snippet failed to work
import java.io.DataOutputStream;import java.net.HttpURLConnection;import java.net.URL;public class HTTPSPlayground { public static void main(String[] args) throws Exception { URL url = new URL("https:// ... .com"); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); httpURLConnection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream()); String serializedMessage = "{}"; wr.writeBytes(serializedMessage); wr.flush(); wr.close(); int responseCode = httpURLConnection.getResponseCode(); System.out.println(responseCode); }}
this is what solved my issue:
1) Download the .crt
file
echo -n | openssl s_client -connect <your domain>:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'> ~/<your domain>.crt
- replace
<your domain>
with your domain (e.g.jossef.com
)
2) Apply the .crt
file in Java's cacerts
certificate store
keytool -import -v -trustcacerts -alias <your domain> -file ~/<your domain>.crt -keystore <JAVA HOME>/jre/lib/security/cacerts -keypass changeit -storepass changeit
- replace
<your domain>
with your domain (e.g.jossef.com
) - replace
<JAVA HOME>
with your java home directory
3) Hack it
Even though iv'e installed my certificate in Java
's default certificate stores, Tomcat ignores that (seems like it's not configured to use Java's default certificate stores).
To hack this, add the following somewhere in your code:
String certificatesTrustStorePath = "<JAVA HOME>/jre/lib/security/cacerts";System.setProperty("javax.net.ssl.trustStore", certificatesTrustStorePath);// ...