Sunday, December 19, 2004

JSSE: How to ignore CertificateException: Couldn't find trusted certificate"?

While testing SecureSocket code, sometimes you would need code to ingore certificate validation.
JSSE provides a simple way to do this by writing your own TrustManager. The below sample code lets you write simple clients ignore certificate validation:

01 
02 
03 import java.io.InputStream;
04 import java.io.OutputStream;
05 
06 import javax.net.ssl.SSLContext;
07 import javax.net.ssl.SSLSocket;
08 import javax.net.ssl.SSLSocketFactory;
09 import javax.net.ssl.TrustManager;
10 import javax.net.ssl.X509TrustManager;
11 
12 /*
13  * This example demostrates how to use a SSLSocket as client to
14  * send and recieve Data while ignoring the certificate validation.
15  */
16 
17 public class SSLClient {
18 
19     public static void main(String[] argsthrows Exception {
20 
21         // Create a trust manager that does not validate certificate chains like the default TrustManager
22         TrustManager[] trustAllCerts = new TrustManager[]{
23             new X509TrustManager() {
24 
25                 public java.security.cert.X509Certificate[] getAcceptedIssuers() {
26                     return null;
27                 }
28 
29                 public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
30                     //No need to implement.
31                 }
32 
33                 public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
34                     //No need to implement.
35                 }
36             }
37         };
38 
39         // Let us create the factory where we can set some parameters for the connection
40         SSLContext sc = SSLContext.getInstance("SSL");
41         sc.init(null, trustAllCerts, new java.security.SecureRandom());
42 
43         SSLSocketFactory factory =sc.getSocketFactory();
44         SSLSocket socket =(SSLSocket)factory.createSocket(args[0], Integer.parseInt(args[1]));
45         socket.startHandshake();
46 
47 
48         OutputStream out = socket.getOutputStream();
49         InputStream in = socket.getInputStream();
50 
51         //Do- Fun stuff with I/O classes.
52     }
53 }

2 comments:

Anonymous said...

Thanks thats really useful.
--C.

Anonymous said...

found another example at jexamples.com. I searched for "javax.net.ssl.SSLContext.init". Example is in Tomcat. fyi.