Skip to Main Content

Java Security

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Java SSL TrustManager

843811Apr 13 2005 — edited Apr 15 2005
Hello,

I'm doing a simple project which concist in creanting a SSL Socket client. This client must connect to a SSL server with a "false" certificate. So it seems that I need to create a trustmanager which accept all the certificate.

Afer serching on internet and on this forum, I wrotte a code which seems ok. But I still have the pb tha the certificate fron the server is not valid !!

Can someone could help me , please ....

Here is all the code of my client (very short):

public class SSLClient2 {
	
	public static final String TARGET_HTTPS_SERVER = "www-appn.comp.nus.edu.sg";
 	public static final int    TARGET_HTTPS_PORT   = 443;
	
	public static void main(String[] args) {
		
		String reqGet = "GET / HTTP/1.1\n\n";
		
	    // Create a trust manager that does not validate certificate chains
		TrustManager[] trustAllCerts = new TrustManager[]{
	 		new X509TrustManager() {
	            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
	            	return null;
	            }
	            public void checkClientTrusted(
	                java.security.cert.X509Certificate[] certs, String authType) {
	            }
	            public void checkServerTrusted(
	                java.security.cert.X509Certificate[] certs, String authType) {
	            }
	        }
	    };
	 
	    // Install the all-trusting trust manager
	    try {
	    	SSLContext sc = SSLContext.getInstance("SSL");
	        sc.init(null,trustAllCerts , new java.security.SecureRandom());
	        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
	    } catch (Exception e) {
	    }
	    //create socket and send/receive stream
	    try {
			Socket socket = SSLSocketFactory.getDefault().createSocket(TARGET_HTTPS_SERVER, TARGET_HTTPS_PORT);//create socket
			
			//output stream
			OutputStream out = socket.getOutputStream();
			out.write(reqGet.getBytes());//send the request (i don't mind if the format is right, the server doesn't care)
			out.flush();
			
			//input stream
			BufferedReader in = new BufferedReader(
			           new InputStreamReader(socket.getInputStream())), "ISO-8859-1"));
			        String line = null;
			        while ((line = in.readLine()) != null) {
			           System.out.println(line);
			        }
		} catch (MalformedURLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
	}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 13 2005
Added on Apr 13 2005
1 comment
845 views