Sunteți pe pagina 1din 88

PREFACE

Today all the phases of life are becoming computerized. Networking


has now become a very important part today. A number of networks and
network protocols have been defined and used today. Anyone can connect to
different types of networks to connect their own hosts (computers) together.
Hence the increase in computerization has increased the use of networking and
so the networking security. This gave us the impetus to our project selection.

Keeping in mind the lack of knowledge the customer/user possess, the


project of ours “SSL(Secure Socket Layer) DEMONSTRATION” is our
humble step to make the users aware about this security. The project
demonstrates the security measures that are taken over the public or private
networks with simple user interface.

It defines various security parameters that are actually established


behind the scene that the user is unaware about. The project defines the scope
and domain of network security analysis and design. Various security
attributes that are exchanged between the two machines to establish a secure
connection between them could be seen here.

We shall be highly obliged to get responses about the same regarding


further improvements and suggestions regarding technical issues.
ACKNOWLEDGEMENT

For the successful completion of any project, it takes the complete


dedication of all the group members and the combined guidelines provided by
the college professors. The project would not have been completed without the
support, guidance and co-operation of several persons to whom we owe our
sincere gratitude.

Firstly we are highly indebted to our class teacher Mr. Sanjay


Wankhede. It was their genuine interest, timely guidance and persuasive
encouragement that has given us the opportunity to put our ideas into reality
and helped us to complete our project work successfully.

We are also very highly grateful to Mr. Rocky Jagtiani for his interest
and encouragement in the progress of our project.

Had it not been the sincere efforts of our project guide Mr. Dilip N. it
would have been the next to impossible for the completion of our project. His
efforts have been very helpful in the development of our project to solve
different problems that have aroused during the implementation of our
application.

Lastly we are highly indebted to all our respondents without whose


co-operation, the project work would not have been completed and the persons
who have indirectly helped us.
INDEX

1. Problem Definition

 Abstract

 Recommended Solution
2. Analysis of the problem definition

3. Object Oriented Designing

 Development of Algorithm

 Explanation of the algorithm

 Explanation of different modules required for


implementation of algorithm.

4. Implementation

 Explanation of modules

5. Conclusion

 Application of the project

 Future Enhancement

Annexure 1:

 Software test report

• White box testing

• Black box testing

Annexure 2:
 List of references

CHAPTER 1
PROBLEM DEFINITION
ABSTRACT

SSL (Secure Socket Layer) is the most popular protocol used in the
Internet for facilitating secure communication. It is a set of specifications that
allow two applications to communicate with each other via the Internet, in a
secure environment. The explosive growth in Internet for supporting E-
commerce and other exchange of sensitive information has highlighted the
need for efficiently supporting secure communications between clients and
servers by establishing a secure channel between them.

SSL allows a web browser or client to authenticate the existence


identity of a website using digital keys and certificates. It also allows for all
information that it sends to be encrypted, ensuring that information cannot be
intercepted or stolen while in transit.

SSL can be conceptually considered as an additional layer in TCP/IP


protocol suite. The SSL layer is located between the Application Layer and
Transport Layer. By convention URL that begins with https (‘s’ refers as
secure HTTP) instead of http: is an SSL connection. This can be observed in
internet application. Logically, it provides a secure pipe between the Web
Browser and Web Server.

Secure Sockets Layer (SSL) technology protects the Web site or any
application and makes it easy for the visitors to trust in three essential ways:

1. An SSL Certificate enables encryption of sensitive information during


online transactions.
2. Each SSL Certificate contains unique, authenticated information about
the certificate owner.
3. A Certificate Authority verifies the identity of the certificate owner
when it is issued.
PROBLEM DEFINITION

The Internet today is a breeding ground for criminal activity. In this


world of Internet, security is a measure issue to maintain the confidentiality,
integrity and protection against the hacker and hactivism.

Home users, small, medium and big corporate all suffer from the threat
of constant attacks from Viruses, Worms and Trojans etc. by hacker. If the
hacker tampers the confidential data flowing through the network, it would be
a threat to an organization or personnel. The receiver would be fooled by the
hacker. Hence, the confidentiality and the integrity of the data is breached.

Since we know that e-commerce business is all about making money,


it’s difficult since consumers don’t feel safe while doing transaction on Web
site’s.

 Exactly how safe is it to submit credit card details over the net?

While most of us do it every day without batting an eyelid, there are


always those horror stories of people who had their bank accounts wiped out
by malicious hackers, or even fraudulent websites.

 How can one tell when a site is safe?


RECOMMENDED SOLUTION

SSL is a solution for:-

 Confidentiality.

 Integrity.

 Non-repudiation.

SSL layer performs encryption on the data received from the


Application layer and adds its own security information required to send the
data securely.

In SSL, data encryption is required for privacy applications, Client


authentication to the Server, and Server authentication to the Client to create
an authenticated channel. Digital signatures for proof of authorship, signatures
on receipts and other data for non-repudiation purposes, integrity of data
ensures non-tampering of the data either intentionally or unintentionally are
used to provide full-proof security.

Since majority people do not have security knowledge over public as


well as private networks, they fail to judge the security of the websites or
unsecured applications that generally lead to demise of customer faith.

When the Client enters his Login details, the details are transferred
securely through the encrypted channel to the Server for authentication. These
entered details are the sensitive information (like Password). These details are
sent in encrypted format so as to avoid hacking of original data i.e. even if the
hacker hacks the encrypted data, modify it, and sends this modified data to the
Server, it would come to know thus by comparing the hash values.
PROGRAMMING LANGUAGE USED:

 Java

Reason being:

The javax.swing and java.awt packages are used to develop GUI of the
Server and Client applications. They provide a rich set of different Java APIs
for building up the two applications.

Java Secure Socket Extension (JSSE) is a set of Java packages that


enable secure internet communication by providing a frame and a 100% pure
Java implementation of the SSL. Security APIs provide a framework for
accessing and developing cryptographic functionality like symmetric or
asymmetric key generations required in our project. Java Security Toolkit
(JSTK) that provided command line utilities to carry the work of setting CA
for Server authentication helped us.
It possesses the following traits:

 Platform Independence

 Extensible

 Object Oriented

 Customizable

 Configurable

SOFTWARE COMPONENTS USED:

1. jdk1.6
2. Text editor (Notepad)

HARDWARE COMPONENTS USED:


1. Local computer

CHAPTER 2
ANALYSIS AND DESIGN
CHAPTER 3
OBJECT ORIENTED DESIGN
DEVELOPMENT OF ALGORITHM:

 STEPS IN ALGORITHM:

step: 1 Create a virtual CA which is acting as a third party between


Client & server.

step: 2 Create a Server.

step: 3 Server request for certificate to CA (to prove himself to be a


genuine Server to the Client).

step: 4 CA provides self signed certificate to CA fro which server


authenticates itself to the client.

step: 5 Importing signed certificate to Server keystore.

step: 6 Create a client.

step: 7 Start server application.

step: 8 Start client application.

step: 9 As client application starts, our SSL encryption algorithm comes


into the picture.
step: 10 First step i.e. Handshake mechanism establishes handshake
between client and server, Due to handshake client-server
authenticate them self to each other.

step: 11 Client enters login details.

step: 12 When client clicks on “OK”, SSL cipher suit does encrypts &
compresses the login details by selecting supported algorithm
exchanged during handshake.

step: 13 Encrypted output send to the server where server does decryption
of the receiver details by selecting appropriate algorithm
exchanged during handshake.

step: 14 Server verifies the details by comparing details with its hash
table.

step: 15 Server responds to the client by 2 way:

A - If details matches “Authentication success”.

B - If detail not matches “Authentication failure”.


EXPLANATION OF ALGORITHM:

1. Steps to show how virtual CA establishes and acts as a third party between
Client & Server for authenticate to each other.

 For setting up a CA of our own, we use our own JSTK utility certtool.
Setting up a CA with certtool is quite straightforward. You do so by
executing the "certtool” command with “setupca”, an option from
JSTK home directory and specifying appropriate parameters:

C:\ssl>%JSTK_HOME%\bin\certtool setupca –password\


Changeit –dn “CN=JSTK Test Root CA,OU=JSTK Operation,\
O=JSTK Inc,C=US "

2. Create a Server.

 Create server keystore server.ks with a private key and self-


signed certificate.

A keystore is a database of key material. Key material is used for


a variety of purposes, including authentication and data integrity. There
are various types of keystores available, including "PKCS12" and
Sun's "JKS."

A truststore is a keystore which is used when making decisions


about what to trust. If you receive some data from an entity that you
already trust, and if you can verify that the entity is the one it claims to
be, then you can assume that the data really came from that entity.( not
used at Server side in our project)

server.ks is created using the following command:

C:\ssl> keytool -genkey -storepass changeit -storetype JCEKS \


-keypass changeit -keystore server.ks \
-dname "CN=Server, OU=X, O=Y, L=Z, S=XY, C=YZ"
3. Server request for certificate to CA (to prove himself to be a genuine
Server to the Client).

A CSR is a digital document binding the identity information


with the public key. It is sent to a CA to verify the fact that the
requestor has the same identity as claimed in the CSR and to issue the
certificate to the requestor.

The process of CSR generation involves generating a public and


private key pair, supplying the identity information and packaging this
information in the appropriate format. Note that the private key itself is
not part of the CSR.

C:\ssl> keytool -certreq -file temp$.csr -storepass changeit \


-storetype JCEKS -keypass changeit -keystore server.ks

4. Issue a CA signed certificate based on the CSR.

C:\ssl> %JSTK_HOME%\bin\certtool issue -csrfile temp$.csr \


-cerfile server.cer -password changeit

5. Importing signed certificate in server.ks.

C:\ssl>keytool -import -file server.cer -storepass changeit


-storetype JCEKS -keypass changeit -keystore server.ks

6. Steps which shows how Handshake protocol established when Client


gets connected to the Server.

step: 1 The client sends a ClientHello message with a list of cipher


suites it is willing to support, highest protocol version supported
by the client, a random number( kept null , so the default random
no. seed would be used) Since a client doesn't know whether it is
talking to a SSLv2, SSLv3 or TLSv1 server, it could use the
SSLv2 format for this message.
step: 2 Based on the ClientHello message, the server selects the
strongest cipher suite supported by both end points and responds
back with a ServerHello message. This message contains
protocol version (3.1 for TLSv1), its random value, a session ID,
and the selected cipher suite and agreed upon compression
method value.

step: 3 The server sends its certificate or certificate chain in a


Certificate message.

step: 4 The server sends a ServerKeyExchange message if it has no


certificate or the certificate is for signing purposes only.

step: 5 Finally, the server sends a ServerHelloDone message. Note that


all messages since the ServerHello message could be packaged
in one SSL record. On receiving all these messages, the client
performs a number of operations: verifies server's certificate,
extracts the public key, creates a secret string called pre-master
secret, and encrypts it using the server's public key.

step: 6 The client sends the encrypted pre-master secret in


ClientKeyExchange message.

step: 7 The client sends a CertificateVerify message having a string


signed by the private key corresponding to the public key of the
certificate sent earlier. This message is not sent if the client did
not send a certificate.

step: 8 The client sends a ChangeCipherSpec message in a separate


SSL record to indicate that now it is switching to the newly
negotiated protocol parameters for subsequent communication.

step: 9 The client sends a Finished message, which is a digest of the


negotiated master secret and concatenated handshake messages.
step: 10 The server sends a ChangeCipherSpec message in a separate
SSL record to indicate switching to the newly negotiated
protocol parameters.

step: 11 The server sends Finished message, which is a digest of the


negotiated master secret and concatenated handshake messages.
The client performs a similar verification on this message as the
server.
 WHEN CLIENT ENTERS LOGIN
DETAILS:

Here we first validate the Login details at client side where we check for
the following:

1. Both the field must NOT be NULL.

2. Login id must be in range of 6-10 character.

3. Password must be in range of 6-10 characters.

4. If above steps are validated move to next step i.e. SSL


encryption by using supported cipher suit of client and server
which has been exchanged during handshake

5. Encrypted login details are now ready to send over server.


CHAPTER 4
IMPLEMENTATION
CLIENT APPLICATION

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.awt.Component;
import java.io.*;
import java.net.*;
import java.security.*;
import javax.net.*;
import javax.net.ssl.*;
import javax.security.cert.*;

public class Client1 extends JFrame


{
static final int port=8443;
static final String KEYSTORE="client.ks";
static final String TRUSTSTORE="client.ts";
static final String STOREPASS="changeit";
static final String ALIASPASS="changeit";
private String[] unamePwd;
private SSLSession session;
private SSLSocketFactory ssf;
private SSLSocket sock;
private InetAddress host;
private JMenuBar menuBar;
private JMenu fileMenu,options ;
private JMenuItem loginItem,exitItem,aboutus,help;
private int flag;
private String ip;
private ImageIcon img;
private JButton jb;
TabUtil u;
private JScrollPane sp;
private JTextArea chatText;
private JTextField chatLine = null;
private static StringBuffer toAppend=new StringBuffer("");
private static StringBuffer toSend=new StringBuffer("");

public static void main( String[] args )


{
try
{
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
InetAddress host=InetAddress.getLocalHost();
Client1 c1=new Client1( "Program Controlled Login",host);
c1.run1();
}
catch(Exception e)
{ e.printStackTrace(); }
}
public Client1( String titleText,InetAddress host)
/*Start Client application*/
{
super( titleText );
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
this.host=host;
initComponents();
setSize( 500, 400 ); setVisible( true );
setResizable(false);
}
private void initComponents()
{
setJMenuBar( buildMenuBar() );
fileMenu.setEnabled(false);
options.setEnabled(false);
getContentPane().setLayout(null);
Color r1=new Color(165,218,250);
getContentPane().setBackground(r1);
chatText=new JTextArea();
chatLine=new JTextField();
sp=new JScrollPane(chatText);
chatText.setEditable(false);
add(sp);
sp.setBounds(25,75,300,200);
add(chatLine);
chatLine.setBounds(25,280,300,20);
chatLine.setEnabled(false);
} /*End: initComponents()*/

private JMenuBar buildMenuBar()


{
menuBar = new JMenuBar();
fileMenu = new JMenu( "Click Me" );
loginItem = new JMenuItem( "Login" );
loginItem.setAccelerator(KeyStroke.getKeyStroke
(KeyEvent.VK_I,InputEvent.SHIFT_MASK));

exitItem = new JMenuItem( "Logout" );


exitItem.setAccelerator(KeyStroke.getKeyStroke
(KeyEvent.VK_O,InputEvent.SHIFT_MASK));

options=new JMenu("Option");

aboutus=new JMenuItem("About Us");


aboutus.setAccelerator(KeyStroke.getKeyStroke
(KeyEvent.VK_A,InputEvent.SHIFT_MASK));

help=new JMenuItem("Help");
help.setAccelerator(KeyStroke.getKeyStroke
(KeyEvent.VK_H,InputEvent.SHIFT_MASK));
loginItem.addActionListener(new ActionListener()
{
public void actionPerformed( ActionEvent event )
{
unamePwd = JOption.showUserLoginDialog(null,"
Login Dialog", "Username: ", "Password: ");
}
});

exitItem.addActionListener(new ActionListener()
{
public void actionPerformed( ActionEvent event )
{
if(JOptionPane.showConfirmDialog(null,"Do you want to
Logout?","LogOut", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE)==0)
{
JOptionPane.showMessageDialog(null,"You have been
successfully LoggedOut" ,"LoggedOut", 1);
dispose();
System.exit( 0 );
}
}
});

aboutus.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
new AboutUs();
}
});
help.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
try
{
callingHTML(new URL("http://localhost/help.htm"));
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
}
});

menuBar.add( fileMenu );
fileMenu.setCursor(Cursor.getPredefinedCursor
(Cursor.HAND_CURSOR));

fileMenu.add( loginItem );
loginItem.setCursor(Cursor.getPredefinedCursor
(Cursor.HAND_CURSOR));
fileMenu.add( exitItem );
exitItem.setCursor(Cursor.getPredefinedCursor
(Cursor.HAND_CURSOR));

menuBar.add(options);
options.setCursor(Cursor.getPredefinedCursor
(Cursor.HAND_CURSOR));

options.add(aboutus);
aboutus.setCursor(Cursor.getPredefinedCursor
(Cursor.HAND_CURSOR));
options.add(help);
help.setCursor(Cursor.getPredefinedCursor
(Cursor.HAND_CURSOR));
return menuBar;
} /*End: buildMenuBar() */

private void callingHTML(URL target)


{
try
{
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler "
+ target.toString());
}
catch (IOException e)
{ e.printStackTrace(); }
} /*End: callingHTML() */

private void run1()


{
try
{
ssf =Client1.getClientSocketFactory("TLS");
sock = (SSLSocket) ssf.createSocket(host, port);
sock.startHandshake();

if(sock.isConnected())
{
JOptionPane.showMessageDialog(this,"Client-Connected”,
"Done", JOptionPane.INFORMATION_MESSAGE);

fileMenu.setEnabled(true);
options.setEnabled(true);
Font f1=new Font("Dialog",Font.BOLD,16);
JLabel l1=new JLabel("Secure channel has been established
between the Client and Server");
add(l1);
l1.setFont(f1);
l1.setBounds(60,20,500,17);

JLabel l2=new JLabel("the Client and Server");


add(l2);
l2.setFont(f1);
l2.setBounds(125,40,200,17);

img=new ImageIcon("ssl-lock.gif");
jb=new JButton(img);
getContentPane().add(jb);
jb.setBounds(380,185,40,40);

jb.setCursor(Cursor.getPredefinedCursor
(Cursor.HAND_CURSOR));
jb.addActionListener(new ActionListener()
{
public void actionPerformed( ActionEvent event)
{
u=new TabUtil();
u.printSocketInfo(sock);
}
});

final BufferedReader fromServer=new BufferedReader


(new InputStreamReader(sock.getInputStream()));

final PrintWriter toServer=new PrintWriter


(sock.getOutputStream(), true);

exitItem.setEnabled(false);

loop1:while(true) /*Open: while(true)*/


{
while(true)
{
if(unamePwd!=null)
{

for(int i=0;i<2;i++)
{ toServer.println(unamePwd[i]);}
break;
}
}
String y=fromServer.readLine();
if(y.equals("y"))
{
JOptionPane.showMessageDialog(this,"Authentication
Successfull","Done",
JOptionPane.INFORMATION_MESSAGE);

flag=1;
}
else
{
JOptionPane.showMessageDialog(this,"Authentication
Failure”, "Failed",JOptionPane.ERROR_MESSAGE);

JOptionPane.showMessageDialog(this,"Enter your details


again”, "Relogin",
JOptionPane.INFORMATION_MESSAGE);

unamePwd=null;
unamePwd = JOption.showUserLoginDialog(null,
"Login Dialog”,"Username:", "Password:");

continue loop1;
}
if(flag==1) /*Open: if(..)1*/
{
loginItem.setEnabled(false);
exitItem.setEnabled(true);

chatLine.setEnabled(true);
chatText.setEnabled(true);

chatLine.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String s = chatLine.getText();
if (!s.equals(""))
{
toAppend.append("OUTGOING: " + s + "\n");
chatLine.selectAll();
toSend.append(s + "\n");
chatText.append(toAppend.toString());
toAppend.setLength(0);

if (toSend.length() != 0)
{
toServer.println(toSend);
toServer.flush();
toSend.setLength(0);
}
}
}
}); break;
} /*End: if(..) 1*/
} /*End: loop1:while(true) */
}
} /*End: try */
catch(ConnectException ce)
{
JOptionPane.showMessageDialog(this,"Please start the Server",
"Error",JOptionPane.ERROR_MESSAGE);
System.exit(0);
}

catch(SSLException se)
{
JOptionPane.showMessageDialog(null,"Server has been shut
down", "Error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
catch(Exception exe)
{
exe.printStackTrace();
}
} /*End: run1() */

private static SSLSocketFactory getClientSocketFactory(String type)


{
if (type.equals("TLS"))
{
SSLSocketFactory ssf = null;
try
{
SSLContext sslcontext = SSLContext.getInstance("SSL");
KeyManagerFactory kmf=

KeyManagerFactory.getInstance("SunX509");
TrustManagerFactory tmf=

TrustManagerFactory.getInstance(“SunX509");
KeyStore ks=KeyStore.getInstance("JCEKS");
KeyStore ts=KeyStore.getInstance("JCEKS");

ks.load(new FileInputStream(KEYSTORE),

STOREPASS.toCharArray());
ts.load(new FileInputStream(TRUSTSTORE),
STOREPASS.toCharArray());
kmf.init(ks,ALIASPASS.toCharArray());
tmf.init(ts);

sslcontext.init(kmf.getKeyManagers(),
tmf.getTrustManagers(),null);
ssf = sslcontext.getSocketFactory();
return ssf;
}
catch(Exception e)
{ e.printStackTrace(); }
}
else
{
return (SSLSocketFactory) SSLSocketFactory.getDefault();
} return null;
} /*End: getClientSocketFactory()*/
} /*End: Client1 class*/

EXPLAINATION
The class Client1.java is the Client side of a secure network connection.
The Java API classes and interfaces to perform the functions of establishing
connection between Client and Server via sockets reside in the packages
java.net and javax.net. They support many different sequences of class
instantiations and method invocations to establish a connection. Many other
packages for building the secure applications are imported.

The run1() in the class Client1 calls the method


getClientSocketFactory(type). Here, in method getClientSocketFactory(type), a
JSSE-specific collection of key managers and trust managers is created, using
the JCEKS keystore objects: ks and ts respectively. The SSL connection will
require access to encryption keys and certificates. For that reason, factory
objects to create both KeyManager and TrustManager objects are created and
then initialized with the KeyStore and TrustStore objects.

An SSLContext object is created with the input parameter, TLS


indicates that we want to use the Transport Layer Security standard. Once the
SSLContext object is created, it is initialized with all the KeyManager and
TrustManager objects that the factory objects support. The SSLSocket object
sock calls a method startHandshake().Starts an SSL handshake on the
established connection. Common reasons include a need to use new encryption
keys, to change cipher suites, or to initiate a new session. The parameters
exchanged during handshake could be viewed on a certificate that is received
from Server (SocketInfo.java).

The random number used in the process of generating the secret key is
kept null, so the default random number seed will be used.

SERVER APPLICATION
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.security.*;
import javax.net.*;
import javax.net.ssl.*;
import javax.security.cert.*;

public class Server1 extends JFrame implements ActionListener


{
static final String STOREPASS="changeit";
static final String ALIASPASS="changeit";
static final String KEYSTORE="server.ks";
private JButton cmdStart;
private SSLSocket sock;
private SSLServerSocket ss;
private SSLServerSocketFactory ssf;
private JLabel j1;
private String a,b;
static final int port=8443;
private JScrollPane sp;
private static JTextArea chatText;
private String s=" ";
private static StringBuffer toAppend=new StringBuffer("");
private static StringBuffer toSend=new StringBuffer("");
private BufferedReader fromClient;
private PrintWriter toClient;
private static int flag;

public static void main(String args[])


{
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
Server1 server=new Server1();
}

public Server1() /* Start Server application*/


{
initComponents();
cmdStart.addActionListener(this);
cmdStart.setCursor(Cursor.getPredefinedCursor
(Cursor.HAND_CURSOR));
setSize(300,320);
setLocationRelativeTo(null);
setVisible(true);
}

private void initComponents()


{
cmdStart = new JButton();
getContentPane().setLayout(null);
setTitle("Server");
setResizable(false);
Color c1=new Color(247,249,164);
getContentPane().setBackground(c1);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent evt)
{
exitForm(evt);
}
});

cmdStart.setText("Start");
getContentPane().add(cmdStart);
cmdStart.setBounds(200, 120, 70, 30);
chatText=new JTextArea();
sp=new JScrollPane(chatText);
chatText.setEditable(false);
add(sp);
sp.setBounds(25,55,155,215);
} /* End: initComponents()*/
private void exitForm(WindowEvent evt)
{
System.exit(0);
}

public void actionPerformed(ActionEvent event)


{
Object source=event.getSource();
try
{
if(source==cmdStart)
{
new MyAsync().start();
}
}
catch(Exception e)
{}
}

private class MyAsync extends Thread


{
public void run()
{
try
{
getContentPane().setLayout(null);

Font f1=new Font("Dialog",Font.BOLD,16);


cmdStart.setEnabled(false);
JLabel l1=new JLabel("Server started");
add(l1);
l1.setFont(f1);
l1.setBounds(80,20,200,25);

ssf = Server1.getServerSocketFactory("TLS");
ss = (SSLServerSocket) ssf.createServerSocket(port);
sock = (SSLSocket) ss.accept();

fromClient =new BufferedReader(new InputStreamReader


(sock.getInputStream()));
toClient = new PrintWriter(sock.getOutputStream(), true);

while (true)
{
try
{
a = fromClient.readLine();
b = fromClient.readLine();

if (a != null & b != null) /*Open: if(..)1 */


{
HT h = new HT();
boolean y = h.welcome(a, b);

if (y == true)
{
getContentPane().setLayout(null);
toClient.println("y");
flag=1;
}

else
{
toClient.println("n");
}
} /*End: if(..)1 */
} /*End: try */
catch (SocketException e)
{
JOptionPane.showMessageDialog(null,"Client is
disconnected", "Error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
catch(Exception exe)
{
exe.printStackTrace();
}

if(flag==1) /*Open: if(..) 2*/


{
chatText.setEnabled(true);

while(true)
{
s = fromClient.readLine();

if ((s != null) && (s.length() != 0))


{
toAppend.append("INCOMING: " + s + "\n");
chatText.append(toAppend.toString());
toAppend.setLength(0);
}
}
} /*End: if(..) 2*/
} /*End: while(true)*/
} /*End: try*/

catch (SocketException e)
{
JOptionPane.showMessageDialog(null, "Client is disconnected",
"Error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
catch (Exception exc)
{ exc.printStackTrace(); }
}
} /*End: MyAsync class*/

private static SSLServerSocketFactory getServerSocketFactory(String type)


{
if (type.equals("TLS"))
{
SSLServerSocketFactory ssf = null;
try
{
SSLContext sslcontext = SSLContext.getInstance("TLS");
KeyManagerFactory kmf= KeyManagerFactory.getInstance
("SunX509");
KeyStore ks=KeyStore.getInstance("JCEKS");

ks.load(new FileInputStream(KEYSTORE),
STOREPASS.toCharArray());
kmf.init(ks,ALIASPASS.toCharArray());
sslcontext.init(kmf.getKeyManagers(),null,null);
ssf = sslcontext.getServerSocketFactory();
return ssf;
}
catch(Exception e)
{
e.printStackTrace();
}
}

else
{
return(SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
} return null;
} /* End: getServerSocketFactory()*/
} /*End: Server1 class*/

EXPLAINATION
The Server1.java is the Server side of a secure network connection.
Similar to Client1.java the Java API classes and interfaces to perform the
functions of establishing connection between Client and Server via sockets
reside in the package java.net and javax.net. Many other packages for building
the secure applications are imported.

When we start the Server, it waits for the Client connection. When the
Server is started a new thread is created i.e. run() method from MyAsync class
is called. This method calls the method getServerSocketFactory(type). In this
method, a JSSE-specific collection of key manager is created, using the
JCEKS keystore object: ks.

When the Keystore is initially created it is an empty object and then


loads it with the contents of the program’s keystore file. The SSL connection
will require access to encryption keys and certificates. For that reason, factory
object to create KeyManager is created and then initialized with the KeyStore
object.

With the groundwork in place with respect to keys and certificates, an


SSLContext object is created with the input parameter; TLS indicates that we
want to use the Transport Layer Security standard. Once the SSLContext object
is created, it is initialized with the entire KeyManager object that the factory
objects support.

The random number used in the process of generating the secret key is
kept null, so the default random number seed will be used.

CHECK LOGIN VALIDATIONS


import java.awt.Component;
import java.awt.*;
import java.io.*;
import javax.swing.*;

class JOption extends JOptionPane


{
static String[] showUserLoginDialog(Component parentComponent,
String title, String label1, String label2)
{
JPanel jp = new JPanel();
String uname=" ",pwd=" ";
jp.setLayout(new GridLayout(3,3));
JTextField username = new JTextField(10);
JPasswordField password = new JPasswordField(10);
JLabel l1=new JLabel(label1);
jp.add(l1);
jp.add(username);
JLabel l2=new JLabel(label2);
jp.add(l2);
jp.add(password);
int n = showConfirmDialog (parentComponent, jp, String title,
JOptionPane.OK_CANCEL_OPTION);

while(true)
{
if(n==OK_OPTION)
{
if(((username.getText().length())==0)&& /*open: if(..) 1*/
((password.getText().length())==0))
{ showMessageDialog(null,"Enter Username and Password" ,
"Error", JOptionPane.ERROR_MESSAGE);
break;
} /*close: if(..) 1*/
else /*open: else 1*/
{
if(((username.getText().length())>=6)&& /*open: if(..) 2*/
((username.getText().length())<=10))
{
uname=username.getText();
} /*close: if(..) 2*/
else /*open: else 2*/
{
if((username.getText().length())==0)
{
showMessageDialog(null, "Username should be of 6-10
characters","Error",JOptionPane.ERROR_MESSAGE);
break;
}
else
{
if(((username.getText().length())<6)||
((username.getText().length())>10))
{
showMessageDialog(null, "Username should be of 6-10
characters","Error",JOptionPane.ERROR_MESSAGE);
break;
}
}
} /*close: else 2*/

if(((password.getText().length())>=6)&& /*open: if(..) 3*/


((password.getText().length())<=10))
{
pwd=password.getText();
} /*close: if(..) 3*/

else /*open: else 3*/


{
if((password.getText().length())==0)
{
showMessageDialog(null,"Password should be atleast of 6 char
and should not exceed 10 char", "Error",
JOptionPane.ERROR_MESSAGE);
break;
}
else
{
if(((password.getText().length())<6)||
((password.getText().length())>=10))
{
showMessageDialog(null,"Password should be atleast of
6 char and should not exceed 10 char", "Error",
JOptionPane.ERROR_MESSAGE);
break;
}
}
} /*close: else 3*/
} /*close: else 1*/
}
else
{
if(n==CANCEL_OPTION)
{
JOptionPane.showMessageDialog(null,"Thank You", "Message",
JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
break;
} /*End: while(true)*/
if((((username.getText().length())>=6)&&
((username.getText().length())<=10))&&
(((password.getText().length())>=6)&&
((password.getText().length())<=10)))
{
String[] unamePwd= new String[] { uname,pwd };
return unamePwd;
}
else
{
return null;
}
} /*End: showUserLoginDialog*/
} /*End JOption class*/

EXPLAINATION

The JOption.java extends the JOptionPane class in Java. JOptionPane


makes it easy to pop up a standard dialog box that prompts users for a value or
informs them of something.

The static method showUserLoginDialog(parent comp, title,


label1,label2) of the class JOption is called from the class Client1 when the
user wants to login to the system.The confirm dialog box is popped up to
accept the login details: Username and Password from the user of the
application.

These are checked to ensure the user enters correct data. The object
with Username and Password: unamePwd is returned back to the class Client1
where the object is passed to the Server through a secure channel in the
encrypted format.
HASHTABLE COMPARISON

import java.util.*;
import java.io.*;

class HT
{
Hashtable log=new Hashtable();
Enumeration e;
private String a,b;
private boolean flag;

HT()
{
log.put(new String("Ashwini"),new String("ashwini"));
log.put(new String("Ashwinip"),new String("ashwinipatil"));
}

boolean welcome(String a,String b)


{
this.a=a;
this.b=b;
e=log.keys();

while(e.hasMoreElements())
{
String bal=(String) e.nextElement();

if(a.equals(bal))
{
if(b.equals((String)log.get(bal)))
{
flag=true;
break;
}
}}
if(flag==true)
{
return true;
}
else
{
return false;
}
} /*End: welcome()*/
} /*End: HT class*/

EXPLAINATION

This class stores the details that are loaded each time HT() is called.
When the Server send the data to this class to check whether the given details
matches with the store details, a welcome(string, string) method is called that
returns a Boolean value.

It returns true if the details match else false.


SOCKET INFORMATION

import javax.net.ssl.*;
import java.net.*;
import java.security.*;
import javax.security.cert.*;
import javax.security.cert.X509Certificate;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.*;
import java.lang.*;
import java.awt.event.*;
import java.math.BigInteger;

public class SocketInfo extends JFrame


{
private JLabel j1;
InetSocketAddress localAddr, remoteAddr;
SSLSession sess;
X509Certificate[] remoteCerts;

public void printSocketInfo(SSLSocket sock)


{
try
{
JFrame.setDefaultLookAndFeelDecorated(true);
sess = (sock).getSession();
remoteCerts = sess.getPeerCertificateChain();

JTabbedPane jtp=new JTabbedPane();


jtp.addTab("General",new CertInfo(sock,sess,remoteCerts));
jtp.addTab("Details",new DetailInfo(sock,sess,remoteCerts));
getContentPane().add(jtp);
setSize(400,500);
setVisible(true);
setResizable(false);
}
catch(Exception e)
{}
} /*End: printSocketInfo() */

class CertInfo extends JPanel


{
Font f1,f2;
CertInfo(SSLSocket sock, SSLSession sess,
X509Certificate[] remoteCerts)
{
setLayout(null);
f1=new Font("Dialog",Font.BOLD,12);

ImageIcon i1=new ImageIcon("cert.gif");


JLabel l1=new JLabel(" Certificate Information ",i1,JLabel.LEFT);
add(l1);
l1.setFont(f1);
l1.setBounds(15,15,300,35);

JLabel l2=new JLabel("------------------------------------------------------


-------------------------------");
add(l2);
l2.setBounds(15,45,385,15);

JLabel l3=new JLabel(" This certificate is intended for the following


purpose(s): ");
add(l3);
l3.setFont(f1);
l3.setBounds(15,55,350,35);

f2=new Font("Dialog",Font.PLAIN,12);
JLabel l4=new JLabel(" All application policies " );
add(l4);
l4.setFont(f2);
l4.setBounds(30,70,300,35);

JLabel l5=new
JLabel("-----------------------------------------------------
---------------------------------");
add(l5);
l5.setBounds(15,200,385,15);

JLabel l6=new JLabel( "Issued to : ");


add(l6);
l6.setFont(f1);
l6.setBounds(15,250,100,35);

JLabel l7=new JLabel( "Issued by : " );


add(l7);
l7.setFont(f1);
l7.setBounds(15,300,100,35);

JLabel l8=new JLabel( "Valid from" );


JLabel l9=new JLabel( "to" );

add(l8);
l8.setFont(f1);
l8.setBounds(15,350,75,35);

add(l9);
l9.setFont(f1);
l9.setBounds(175,350,30,35);

String dn[]=new String[2];


String cn[]=new String[2];
try
{
for (int i = 0; i < remoteCerts.length; i++)
{
dn[i] = remoteCerts[i].getSubjectDN().getName();
cn[i]=getCN(dn[i]);
}
JLabel l10=new JLabel(cn[0]);
add(l10);
l10.setBounds(90,250,100,35);
l10.setFont(f2);

JLabel l11=new JLabel(cn[1]);


add(l11);
l11.setBounds(90,300,150,35);
l11.setFont(f2);

Date d1=remoteCerts[0].getNotBefore();
Date d2=remoteCerts[0].getNotAfter();

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");

String s2=sdf.format(d1).toString();
String s4=sdf.format(d2).toString();

JLabel l12=new JLabel(s2);


add(l12);
l12.setBounds(90,350,50,35);
l12.setFont(f2);

JLabel l13=new JLabel(s4);


add(l13);
l13.setBounds(225,350,50,35);
l13.setFont(f2);
}

catch (Exception exc)


{
exc.printStackTrace();
}
} /*End: CertInfo() */

private String getCN(String dn)


{
int i=0;
i = dn.indexOf("CN=");
if (i == -1)
{ return null; }

dn = dn.substring(i + 3);
char[] dncs = dn.toCharArray();

for (i = 0; i < dncs.length; i++)


{
if (dncs[i] == ',' && i > 0 && dncs[i - 1] != '\\')
{break;}
}
return dn.substring(0, i);
} /*End: getCN()*/
} /*End: CertInfo class*/

class DetailInfo extends JPanel


{
JTextArea jta=new JTextArea();

DetailInfo(SSLSocket sock, SSLSession sess,


X509Certificate[] remoteCerts)
{
try
{
setLayout(null);
String proto=sess.getProtocol();
int i=remoteCerts[0].getVersion();

BigInteger b=remoteCerts[0].getSerialNumber();
String sn=b.toString(16);

String suite=sess.getCipherSuite();
String signalg=remoteCerts[0].getSigAlgName();

Principal p1=remoteCerts[0].getIssuerDN();
String pIssue=p1.toString();

String d1=remoteCerts[0].getNotBefore().toString();
String d2=remoteCerts[0].getNotAfter().toString();

Principal p2=remoteCerts[0].getSubjectDN();
String pSub=p2.toString();

PublicKey key1=remoteCerts[0].getPublicKey();
String pubKey=key1.toString();

InetSocketAddress remoteAddr;
remoteAddr= (InetSocketAddress) sock.getRemoteSocketAddress();
String remote=remoteAddr.toString();

String col[]={"Field","Value"};
String data[] []={{"Protocol Version",proto},
{"Serial Number",sn},
{"Cipher Suite",suite},
{"Signature Algorithm",signalg},
{"Issuer",pIssue},
{"Valid from",d1},
{"Valid to",d2},
{"Subject",pSub},
{"Public key",pubKey},
{"Remote Address",remote}
};

final JTable table = new JTable(data,col)


{
public boolean isCellEditable(int rowIndex, int colIndex)
{
return false; //Disallow the editing of any cell
}
};

table.setRowHeight(20);
add(jta);

jta.setEditable(false);
jta.setLineWrap(true);

JScrollPane outputPane = new JScrollPane(jta,


JScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

add(outputPane);
outputPane.setBounds(25,250,325,150);

table.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{ printData(table); }
});

JScrollPane pane = new JScrollPane(table);


add(pane);
pane.setBounds(25,20,325,125);
}
catch(Exception e)
{}
} /*End: DetailInfo() */

private void printData(JTable table)


{
int Row = table.getSelectedRow();
int Col = table.getSelectedColumn();
TableModel model = table.getModel();
jta.setText("");
if(Col==1)
{
jta.append((String)model.getValueAt(Row, Col));
}
else
{
jta.append((String)model.getValueAt(Row, Col+1));
}
} /*End: printData() */
} /*End:DetailInfo class*/

EXPLAINATION

The SocketInfo class is created to display the certificate information of the


Server to the Client in CertInfo class. The method getCN() from class CertInfo
retrieves the Domain Name (DN) of the entities. All the necessary certificate
infotmation is displayed here on JFrame since we cannot retrieve the entire
certificate directly. Hence, we have retrieved only certificate information.

It also displays all the information that is exchanged between the Server and
the Client in DetailInfo class which include protocol version, cipher suite, signature
algorithm etc. Hance, this class displays all the socket information.

GUI SNAPSHOTS
 Screen 1: Server.

 Screen 2: Client connected to the Server

 Screen 3: Secure channel established


Here, when the Client gets connected to the Server, it displays “Secure
channel has been established between the Client and Server” on Client
application. This means the SSL algorithm is working in the background.

All the Certificate information can be viewed when clicked on .


 Screen 4: Certificate- General

This Certificate is displayed when clicked on .

It displays the Server certificate to the Client. It includes the


information that proves that the Server is genuine.
 Screen 5: Certificate- Details

This displays the details that are exchanged between the Client and
Server during handshake. It includes the information regarding the cipher suite
that is being selected and used while secure transmission of data, the 1024 bits
public key of the Server, and other information.

This is 1024 bits public key of the Server that it is uses during
communication.
 Screen 6: Login Dialog

The login dialog box pops up to accept the Username and Password
from the user of the application when the user clicks on Login or Shift+L on
MenuBar within Click Me option..
 Screen 7: Successful Authentication

When clicked on OK on login pop up dialog box, the data passes


securely encrypted using supported cipher suite and the private key of the
Client and Public key of the Server. The data when received at Server end is
first decrypted using its private key, public key of the user and supported
cipher suite(selected during handshake) and compares with the stored detail.

If the entered details match with the stores details at Server , the Server
sends positive response to the Client and hence the Client application displays
“Authentication Successful” else “Authentication Failure”.
 Screen 8: Messages exchanged through secure channel.

The messages here are exchanged through secure channel between


Client and the Server. Only the Client can send messages, the Server here does
not respond back to the messages that are received from Client.
 Screen 8: Server not started.

When the Client tries to connect with the Server and if the Server has
not been started initially, it pops up a message “Please start the Server” and
exits the application.
 Screen 9: Help File

The HTML help file created gives the information on the entire topic of
SSL. It describes the detail algorithm that has been implemented in our project.

It also gives the detail information on how to use our project along with
the screenshots to make it more understandable and easy.

It explains the need of SSL today and the future applications of the
same, different mechanisms used in developing a strong security in the
network applications. How security is thus maintained between a Client and
Server.
CHAPTER 5
CONCLUSION
APPLICATIONS

PRESENT APPLICATIONS OF THE PROJECT:

 SSL (Secure Socket Layer) is used in Password protection i.e. it is


used to travel the password securely from one application to
another.

 Used in sending any confidential data like license numbers, credit


card numbers securely.

 Client maintains an ongoing communication with the Server


through a secure channel established between them. Hence, data
passes securely to the Server.

FUTURE ENHANCEMENTS:

 Server requests the Client certificate for Client Authentication to


prove the Client is genuine.

 It can be implemented over Intranet.

 It can be used to implement security on websites.

 Can be made more secure and flexible way to access data remotely
by implementing different cipher suites and usage of firewalls to
block the access to the secure resource over network.
APPLICATIONS DUE TO FUTURE ENHANCEMENTS:

 Use of the Client authentication assures that the person represented


by the Certificate is the person that is expected. Hence, only the
genuine Clients would be allowed to access the remote
confidential data or resources.

 SSL is a key to E-commerce and Banking security. This can be


used over E-commerce and Banking websites where online
transactions are needed to be done securely.

 Can be used on an Intranet, if it is likely to be passing some


sensitive business data around.

 SSL VPNs give a flexible and secure way to extend network


resources to virtually any remote user with access to the Internet
and a Web browser.
ANNEXURE 1

BLACK BOX TEST REPORT


Sr. Expected
Description Inputs Actual Results Status
no. Results
Create Keystore created Keystore created
1 --- Pass
server.ks successfully successfully
Create Keystore created Keystore created
2 --- Pass
client.ks successfully successfully
Start Server Server should get Server not
3 --- Fail
application started started
Start Client Client should get
4 --- Client not started Fail
application started
Start Client
Display “Please Connect
5 before --- Fail
start the Server” Exception raised
Server
Enter
Username-“ Should display Displays
6 Ashwini” & “Authentication “Authentication Pass
Password- Successful” Successful”
“ashwini”
Should display
Do not enter Displays “Enter
“Enter
7 details. Click Username & Pass
Username &
“OK” Password”
Password”
Validating Enter Should display
Displays “Enter
8 inputs Username error-“Enter Pass
Password”
only Password”

Enter Should display


Displays “Enter
9 Password error-“Enter Pass
Username”
only Username”
Should display Displays
Enter “Username “Username
10 Username should be should be Pass
out of range between 6-10 between 6-10
chars” chars”
Should display Displays
Enter “Password “Password
11 Password out should be should be Pass
of range between 6-10 between 6-10
Validating chars” chars”
inputs Should be
displayed at the
Close the SSL Exception
12 Client “Server Fail
Server raised
has been
shutdown”
Retrieve
13 CN from --- Display only CN Not displayed Fail
DN
Display
table Value Should display
in only the Value
14 --- Not displayed Fail
Certificate field when
to the clicked
TextArea
Display the
Should display
date in a
15 --- in this format on Not displayed Fail
“dd/MM/yy”
Certficate
format
Load data
dynamically
Details from
in Did not compare
Server to the
16 Hashtable Should compare since data was Fail
Hashtable for
when data is not loaded
comparison
passed to
the Server

WHITE BOX TEST REPORT


Sr. Expected
Description Inputs Actual Results Status
no. Results
Server started.
Load server.ks
Start Server Server should & initialize
1 --- Pass
application get started SSLContext
object with
keyManagers
Client started.
Load client.ks &
Start Client Client should get initialize
2 --- Pass
application started SSLContext
object with
keyManagers
Placed a pop up
dialog box in
catch(). Since
Start Client
Display “Please Connection is
3 before --- Pass
start the Server” not established
Server
between Client
& Server to start
communication
Placed a pop up
Should be dialog box
displayed at the catch(). Since
Close the
4 Client “Server Connection is Pass
Server
has been broken between
shutdown” the Client and
Validating
Server
inputs
Usage of
Retrieve CN getCN()-not a
5 Display only CN Pass
from DN predefined
method

6 Validating Display table Should display Usage of Pass


inputs Value in only the Value printData() –not
Certificate to field when a predefined
the TextArea clicked method
Display the Usage of
Should display in
date in a SimpleDateFor
7 --- this format on Pass
“dd/MM/yy” mat-predefined
Certficate
format class
The datails were
Load data
compared by
dynamically Details from
using HT()
in Hashtable Server to the
8 Should compare constructor that Pass
when data is Hashtable for
dynamically
passed to the comparison
inserted data in
Server
the Hashtable
ANNEXURE 2

LIST OF REFERENCES

BOOKS REFERRED:
 JAVA Complete Reference by Herbert Schildt.

 JAVA2 Network Securit by Marco Piasto.

 J2EE Security by Pankaj Kumar.

 JAVA Security Solutions by Rich Helton and Johennie Helton.

 JAVA Programming: Advanced Topicd by Joe Wigglesworth.

PROJECT IDEAS:
 www.planetsourcecode.com

 www.ieeexplore.ieee.org

 www.rockysir.info

 www.crazyengineers.com/forum/project-ideas

 www.projectideas.blogspot.com

INFORMATION ON SSL (Secure Socket Layer):

 www.docs.sun.com
 www.stilius.net/java/java_ssl.com
 www.java.sun.com/j2se/1.5.0/docs/guide/
security/jsse/JSSERefGuide.html

 www.ietf.org

 www.ssl-protocol.blogspot.com

TO SOLVE JAVA CODING PROBLEMS:


 www.java2s.com

 www.roseindia.net

 www.javaworld.com

CONTACT INFORMATION:
For any queries please contact:

 Ashwini P. Patil

patil.ashu01@gmail.com

 Ashish Pandya

ashishpandya50@gmail.com

 Santosh Vaidya

santy.aries@gmail.com

 Gaurav Shroff

gauravshroff555@gmail.com
THANK YOU

S-ar putea să vă placă și