Saturday, October 10, 2009

SSL Implementation – Java Source Code

In my earlier article, I have given the highlights the basics of one way and two way ssl.
This article will help you to implement one way SSL and two way SSL using Java.

Before proceeding into the codes, I would like to explain few terms and concepts which will help you to understand the code in a better way.

Using certificates for privacy and security

You can use certificates to protect your personally identifiable information on the Internet and to protect your computer from unsafe software. A certificate is a statement verifying the identity of a person or the security of a Web site.

Internet Explorer uses two different types of certificates:


A personal certificate is a verification that you are who you say you are. This information is used when you send personal information over the Internet to a Web site that requires a certificate verifying your identity. You can control the use of your identity by having a private key on your computer. When used with e-mail programs, security certificates with private keys are also known as "digital IDs".


A Web site certificate states that a specific Web site is secure and genuine. It ensures that no other Web site can assume the identity of the original secure site. When you are sending personal information over the Internet, it is a good idea to check the certificate of the Web site you are using to make sure that it will protect your personally identifiable information. When you are downloading software from a Web site, you can use certificates to verify that the software is coming from a known, reliable source.

[Source: Microsoft Internet Explorer Help]

How do security certificates work?

A security certificate, whether it is a personal certificate or a Web site certificate, associates an identity with a public key. Only the owner of the certificate knows the corresponding private key. The private key allows the owner to make a digital signature or decrypt information encrypted with the corresponding public key. When you send your certificate to other people, you are actually giving them your public key, so they can send you encrypted information that only you can decrypt and read with your private key.

The digital signature component of a security certificate is your electronic identity card. The digital signature tells the recipient that the information actually came from you and has not been forged or tampered with.

Before you can start sending encrypted or digitally signed information, you must obtain a certificate and set up Internet Explorer to use it. When you visit a secure Web site (one whose address starts with https), the site automatically sends you its certificate.

[Source: Microsoft Internet Explorer Help]

KeyStore and TrustStore

A keystore contains a private key. You only need this if you are a server, or if the server requires client authentication.

A truststore contains CA certifcates to trust. If your server's certificate is signed by a recognized CA, the default truststore will already trust it (because it already trusts trustworthy CAs), so you don't need to build your own, or to add anything to the one from the JRE.

You always need a truststore that points to a file containing trusted certificates, no matter whether you are implementing the server or the client side of the protocol, with one exception. This file is often has a name like cacerts, and by default it may turn out to be a file named cacerts in your jre security directory.

You may or may not need a keystore. The keystore points to a file containing private key material. You need a keystore if 1) you are implementing the server side of the protocol, or 2) you are implementing the client side and you need to authenticate yourself to the server.

SSL provides you with privacy, integrity, and authentication. That is, the messages are encrypted, tamper-evident, and come from an authenticated identity. Whether that's the identity you want to talk to is another question. So the application has to perform the authorization step, i.e. check the identity against what is expected. You do this by getting the peer certificates out of the SSLSession, usually in a HandshakeCompletedListener, and check that the identity of the server is what you expect. SSL can't do this for you as only the application knows who it expects to talk to. Another way around this is to ship a custom truststore that only contains the server certificate for the correct server, so it won't trust anybody else.

AccessUrlSSL.java

/*
Implementation of one way and two way SSL using Java
You can change the mode of the program from one way SSL to two way SSL by changing the flag "oneWaySSL"
If oneWaySSL = true then OneWaySSL, if false then Two Way SSL.

If you need to give proper URL.

Also you need to set the property of:

1. TrustStore location and TrustStore Password to implement one way ssl.
2. KeyStore Location, KeyStorePassword and TrustStore Location, TrustStorePassword to implement two way ssl.
*/
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

public class AccessUrlSSL{

AccessUrlSSL(){
}

private void doUpload(){
boolean oneWaySSL = false; // One Way SSL [true] and Two Way SSL [false]
if(oneWaySSL){
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
System.out.println("Warning: URL Host: "+urlHostName+" vs. "+session.getPeerHost());
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
try {
System.setProperty("https.proxySet","true");
System.setProperty("https.proxyHost","internet proxy address");
System.setProperty("https.proxyPort","8080");
System.setProperty("https.proxyType","4");
if(oneWaySSL){
System.setProperty("javax.net.ssl.trustStore","trustStoreLocation");
System.setProperty("javax.net.ssl.trustStorePassword","passw0rd");
}else{
System.setProperty("java.protocol.handler.pkgs","javax.net.ssl");
System.setProperty("javax.net.ssl.keyStore","keystoreLocation"); //KeyStoreLocation - contains the private keys
System.setProperty("javax.net.ssl.keyStorePassword","passw0rd");
System.setProperty("javax.net.ssl.trustStore","trustStoreLocation"); //TrustStoreLocation - contains the trusted sites
System.setProperty("javax.net.ssl.trustStorePassword","passw0rd");
}

if(oneWaySSL){
URL url = new URL("https","siteLocation",443,"siteFolder");
} else {
URL url = new URL("https","siteLocation",443,"siteFolder");
}
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Content-Type", "multipart/form-data;boundary=vxvxv");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String str = "";
boolean startPrint = false;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (MalformedURLException me) {
me.printStackTrace();
} catch (IOException ie) {
ie.printStackTrace();
} catch(Exception e){
e.printStackTrace();
}
}

public static void main(String args[]){
AccessUrlSSL accessUrlSSl = new AccessUrlSSL();
accessUrlSSl.doUpload();
}

}

Suggestions and feedback please.

1 comment:

Scorp said...

Thanks for sharing this!

Total Pageviews