Network security Lab - Manuals
1. Write a networking program in Java to
implement a TCP server that provides
services for a TCP Client.
Client.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class Client
{
public void go() throws IOException
{
System.out.println("Getting some good
advice...");
Socket socket = new
Socket("localhost",5555);
BufferedReader
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String advice = reader.readLine();
System.out.println(advice);
reader.close();
socket.close();
}
public static void
main(String[] args) throws IOException
{
Client client = new Client();
client.go();
}
}
Server.java
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class Server
{
private final static Random random = new Random();
private final static String[] ADVICE_LIST = {
"Take smaller bites",
"Go for the tight jeans. No they do NOT make you look fat.",
"One word: inappropriate",
"Just for today, be honest. Tell yourboss what you *really*
think",
"You might want to rethink that haircut."
};
private void go() throws IOException
{
ServerSocket serverSocket = new ServerSocket(5555);
while(!serverSocket.isClosed()) {
Socket socket = serverSocket.accept();
PrintWriter writer = new
PrintWriter(socket.getOutputStream());
String advice = getAdvice();
System.out.println("Sending
advice: " + advice);
writer.write(advice);
writer.close();
System.out.println("Advice
sent!");
socket.close();
}
}
private static String getAdvice()
{
return ADVICE_LIST[random.nextInt() % ADVICE_LIST.length];
}
public static void main(String[] args) throws IOException
{
Server server = new Server();
server.go();
}
}
Output
2. Write a networking program to
implement socket programming using User
datagram Protocol in Java.
SimpleUDPClient.java
import java.io.IOException;
import java.net.*;
public class SimpleUDPClient
{
public static void main(String[] args){
DatagramSocket socket = null;
DatagramPacket inPacket = null;
DatagramPacket outPacket = null;
byte[] inBuf, outBuf;
final int PORT = 4578;
String msg = null;
try
{
InetAddress address =
InetAddress.getByName("127.0.0.1");
socket = new DatagramSocket();
msg = "Hello";
outBuf = msg.getBytes();
outPacket = new DatagramPacket(outBuf, 0,
outBuf.length,
address, PORT);
socket.send(outPacket);
inBuf = new byte[256];
inPacket = new DatagramPacket(inBuf,
inBuf.length);
socket.receive(inPacket);
String data = new String(inPacket.getData(),
0, inPacket.getLength());
System.out.println("Server : "
+ data);
}
catch (IOException ioe)
{
System.out.println(ioe);
}
}
}
Server.java
import java.io.IOException;
import java.net.*;
public class SimpleUDPServer
{
public static void main(String[] args){
DatagramSocket socket = null;
DatagramPacket inPacket = null; //recieving
packet
DatagramPacket outPacket = null; //sending
packet
byte[] inBuf, outBuf;
String msg;
final int PORT = 4578;
try
{
socket = new DatagramSocket(PORT);
while(true)
{
System.out.println("Waiting for
client...");
inBuf = new byte[256];
inPacket = new DatagramPacket(inBuf,
inBuf.length);
socket.receive(inPacket);
int source_port = inPacket.getPort();
InetAddress source_address =
inPacket.getAddress();
msg = new String(inPacket.getData(), 0,
inPacket.getLength());
System.out.println("Client "
+ source_address + ":" + msg);
msg = reverseString(msg.trim());
outBuf = msg.getBytes();
outPacket = new DatagramPacket(outBuf,
0, outBuf.length,
source_address,
source_port);
socket.send(outPacket);
}
}catch(IOException ioe)
{
ioe.printStackTrace();
}
}
private static String reverseString(String input)
{
StringBuilder buf = new StringBuilder(input);
return buf.reverse().toString();
}
}
Output
3. Implement an FTP server using socket
programming.
UDPSocketClient.java
import java.io.IOException;
import java.net.*;
public class UDPSocketClient
{
DatagramSocket Socket;
public UDPSocketClient()
{
}
public void createAndListenSocket()
{
try
{
Socket = new DatagramSocket();
InetAddress
IPAddress = InetAddress.getByName("localhost");
byte[] incomingData = new
byte[1024];
String sentence = "This is a
message from client";
byte[] data = sentence.getBytes();
DatagramPacket
sendPacket = new DatagramPacket(data, data.length, IPAddress, 9876);
Socket.send(sendPacket);
System.out.println("Message sent from
client");
DatagramPacket
incomingPacket = new DatagramPacket(incomingData, incomingData.length);
Socket.receive(incomingPacket);
String response = new
String(incomingPacket.getData());
System.out.println("Response from
server:" + response);
Socket.close();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (SocketException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
UDPSocketClient client = new
UDPSocketClient();
client.createAndListenSocket();
}
}
UDPSocketServer.java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class UDPSocketServer
{
DatagramSocket
socket = null;
public UDPSocketServer()
{
}
public void createAndListenSocket()
{
try
{
socket = new DatagramSocket(9876);
byte[] incomingData = new
byte[1024];
while (true)
{
DatagramPacket
incomingPacket = new DatagramPacket(incomingData, incomingData.length);
socket.receive(incomingPacket);
String message = new
String(incomingPacket.getData());
System.out.println("Received
message from client: " + message);
InetAddress IPAddress =
incomingPacket.getAddress();
int port = incomingPacket.getPort();
String reply = "Thank you for the
message";
byte[] data = reply.getBytes();
DatagramPacket replyPacket =
new DatagramPacket(data, data.length,
IPAddress, port);
socket.send(replyPacket);
Thread.sleep(2000);
socket.close();
}
}
catch
(SocketException e)
{
e.printStackTrace();
- }
catch
(IOException i)
{
i.printStackTrace();
}
catch
(InterruptedException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
UDPSocketServer server = new
UDPSocketServer();
server.createAndListenSocket();
}
}
Output
4. Implement a chat server using socket
programming.
ChatClient.java
import java.io.*;
import java.util.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import static java.lang.System.out;
public class ChatClient extends JFrame implements
ActionListener
{
String uname;
PrintWriter pw;
BufferedReader br;
JTextArea taMessages;
JTextField tfInput;
JButton btnSend,btnExit;
Socket client;
public ChatClient(String uname,String servername) throws Exception
{
super(uname);
this.uname = uname;
client = new
Socket(servername,9999);
br = new BufferedReader( new InputStreamReader( client.getInputStream())
) ;
pw = new PrintWriter(client.getOutputStream(),true);
pw.println(uname);
buildInterface();
new MessagesThread().start();
}
public void buildInterface()
{
btnSend = new JButton("Send");
btnExit = new JButton("Exit");
taMessages = new JTextArea();
taMessages.setRows(10);
taMessages.setColumns(50);
taMessages.setEditable(false);
tfInput = new JTextField(50);
JScrollPane sp = new JScrollPane(taMessages,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
add(sp,"Center");
JPanel bp = new JPanel( new FlowLayout());
bp.add(tfInput);
bp.add(btnSend);
bp.add(btnExit);
add(bp,"South");
btnSend.addActionListener(this);
btnExit.addActionListener(this);
setSize(500,300);
setVisible(true);
pack();
}
public void actionPerformed(ActionEvent evt) {
if ( evt.getSource() == btnExit ) {
pw.println("end");
System.exit(0);
}
Else
{
pw.println(tfInput.getText());
}
}
public static void main(String ... args)
{
String name =
JOptionPane.showInputDialog(null,"Enter your name :",
"Username",
JOptionPane.PLAIN_MESSAGE);
String servername = "localhost";
Try
{
new ChatClient( name ,servername);
}
catch(Exception ex)
{
out.println( "Error -->
" + ex.getMessage());
}
}
class MessagesThread extends
Thread
{
public void run()
{
String line;
Try
{
while(true)
{
line = br.readLine();
taMessages.append(line +
"\n");
}
} catch(Exception ex) {}
}
}
}
Output
5. Implement an ECHO server using socket
programming.
EchoClient.java
import java.io.*;
import java.net.*;
public class EchoClient
{
public
static void main(String[] args)
{
try
{
Socket
s = new Socket("127.0.0.1", 9999);
BufferedReader
r = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter
w = new PrintWriter(s.getOutputStream(), true);
BufferedReader
con = new BufferedReader(new InputStreamReader(System.in));
String
line;
do
{
line
= r.readLine();
if
( line != null )
System.out.println(line);
line
= con.readLine();
w.println(line);
}
while
( !line.trim().equals("bye") );
}
catch
(Exception err)
{
System.err.println(err);
}
}
}
EchoServer.java
import java.io.*;
import java.net.*;
public class EchoServer
{
public
EchoServer(int portnum)
{
try
{
server
= new ServerSocket(portnum);
}
catch
(Exception err)
{
System.out.println(err);
}
}
public
void serve()
{
try
{
while
(true)
{
Socket
client = server.accept();
BufferedReader
r = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter
w = new PrintWriter(client.getOutputStream(), true);
w.println("Welcome
to the Java EchoServer. Type 'bye' to
close.");
String
line;
do
{
line
= r.readLine();
if
( line != null )
w.println("Got:
"+ line);
}
while
( !line.trim().equals("bye") );
client.close();
}
}
catch
(Exception err)
{
System.err.println(err);
}
}
public
static void main(String[] args)
{
EchoServer
s = new EchoServer(9999);
s.serve();
}
private
ServerSocket server;
}
Output
6. Implement Address Resolution Protocol
using socket programming.
Clientarp12.java
import java.io.*;
import java.net.*;
import java.util.*;
class Clientarp12
{
public static void main(String
args[])
{
try
{
DatagramSocket client=new
DatagramSocket();
InetAddress
addr=InetAddress.getByName("127.0.0.1");
byte[] sendbyte=new
byte[1024];
byte[] receivebyte=new
byte[1024];
BufferedReader in=new
BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the logical address (IP):");
String
str=in.readLine();
sendbyte=str.getBytes();
DatagramPacket
sender=new DatagramPacket(sendbyte,sendbyte.length,addr,1309);
client.send(sender);
DatagramPacket
receiver=new DatagramPacket(receivebyte,receivebyte.length);
client.receive(receiver);
String s=new
String(receiver.getData());
System.out.println("The Physical Address is(MAC):
"+s.trim());
client.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Serverarp12.java
import java.io.*;
import java.net.*;
import java.util.*;
class Serverarp12
{
public static void main(String
args[])
{
try
{
DatagramSocket
server=new DatagramSocket(1309);
while(true)
{
byte[]
sendbyte=new byte[1024];
byte[]
receivebyte=new byte[1024];
DatagramPacket receiver=new
DatagramPacket(receivebyte,receivebyte.length);
server.receive(receiver);
String
str=new String(receiver.getData());
String
s=str.trim();
//System.out.println(s);
InetAddress
addr=receiver.getAddress();
int
port=receiver.getPort();
String
ip[]={"165.165.80.80","165.165.79.1"};
String
mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
for(int
i=0;i<ip.length;i++)
{
if(s.equals(ip[i]))
{
sendbyte=mac[i].getBytes();
DatagramPacket sender=new
DatagramPacket(sendbyte,sendbyte.length,addr,port);
server.send(sender);
break;
}
}
break;
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output
7. Implement Ping server and Ping client
using socket programming.
pingclient.java
import java.io.*;
import java.net.*;
public class pingclient
{
public static void main(String
args[])throws IOException
{
String sip=new
String();
Socket s=new
Socket("127.0.0.1",8081);
OutputStream
os=s.getOutputStream();
PrintWriter out=new
PrintWriter(new BufferedWriter(new
OutputStreamWriter(s.getOutputStream())),true);
DataInputStream
in=new DataInputStream(System.in);
System.out.println("Enter the IP address of the ping");
sip=in.readLine();
out.println(sip);
s.close();
}
}
pingserver.java
import java.io.*;
import java.net.*;
import java.lang.*;
public class pingserver
{
public static void main(String
args[])throws IOException
{
String sip;
ServerSocket ss=new
ServerSocket(8081);
Socket s=ss.accept();
BufferedReader in=new
BufferedReader(new InputStreamReader(s.getInputStream()));
sip=in.readLine();
Runtime r=Runtime.getRuntime();
try
{
Process
p=r.exec("ping "+sip);
System.out.println("Executing the command from client
ping"+sip);
in=new
BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while((line=in.readLine())!=null) {
System.out.println(line);
}
in.close();
}
catch(Exception e) {
System.out.println("Error"+e);
}
} }
Output
8. Implement Single Window
Protocol.
wnd2client.java
import java.io.*;
import java.net.*;
public class wnd2client
{
public static void main(String
args[])
{
String se;
try
{
DatagramSocket
s=new DatagramSocket();
do
{
System.out.println("Enter the data");
DataInputStream in=new DataInputStream(System.in);
InetAddress
ipa=InetAddress.getByName("127.0.0.1");
byte[]
sdata=new byte[1024];
byte[]
rdata=new byte[1024];
se=in.readLine();
sdata=se.getBytes();
System.out.println("Hai "+se);
DatagramPacket spack=new DatagramPacket(sdata,sdata.length,ipa,9876);
s.send(spack);
DatagramPacket rpack=new
DatagramPacket(rdata,rdata.length);
s.receive(rpack);
String
modse=new String(rpack.getData());
System.out.println("From server : "+modse);
}
while(!se.equalsIgnoreCase("End"));
s.close();
}
catch(Exception e)
{
System.out.println("Error:"+e);
}
}
}
wnd2server.java
import java.io.*;
import java.net.*;
public class wnd2server
{
public static void main(String args[])throws
IOException
{
DatagramSocket s=new
DatagramSocket(9876);
byte[] sdata=new
byte[1024];
byte[] rdata=new
byte[1024];
String se;
try
{
do
{
DatagramPacket
rpack=new DatagramPacket(rdata,rdata.length);
s.receive(rpack);
String sen=new
String(rpack.getData());
System.out.println("Received from client : "+sen);
InetAddress
ipa=rpack.getAddress();
System.out.println("Address"+ipa);
int
port=rpack.getPort();
System.out.println("port"+port);
System.out.println("Enter the value to send");
DataInputStream
in=new DataInputStream(System.in);
se=in.readLine();
sdata=se.getBytes();
DatagramPacket
spack=new DatagramPacket(sdata,sdata.length,ipa,port);
s.send(spack);
}
while(!se.equalsIgnoreCase("End"));
s.close();
}
catch(Exception e)
{
System.out.println("Error:"+e);
}
}
}
Output
9. Implement Remote Command Execution
using network programming.
remserver.java
import java.io.*;
import
java.net.*;
public class remserver
{
public static void
main(String args[])throws IOException
{
ServerSocket ss=new
ServerSocket(8081);
Socket s=ss.accept();
String cmd;
BufferedReader in=new
BufferedReader(new InputStreamReader(s.getInputStream()));
cmd=in.readLine();
try
{
Runtime
r=Runtime.getRuntime();
Process
a=r.exec(cmd);
System.out.println("Executing command : "+cmd);
}
catch(Exception e)
{
System.out.println("Error"+e);
}
s.close();
}
}
remclient.java
import java.io.*;
import java.net.*;
public class remclient
{
public static void main(String
args[])throws IOException
{
try
{
Socket s=new Socket("127.0.0.1",8081);
PrintWriter out=new
PrintWriter(s.getOutputStream(),true);
String cmd;
DataInputStream in=new
DataInputStream(System.in);
System.out.println("Enter the command to execute on server :
");
cmd=in.readLine();
out.println(cmd);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output
10. Using Remote Method Invocation
distribute the processing to three nodes.
Serverrpc.java
import java.io.*;
import java.net.*;
import java.util.*;
class Serverrpc
{
public static void main(String
args[])
{
try
{
ServerSocket
obj=new ServerSocket(139);
while(true)
{
Socket obj1=obj.accept();
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStream dout=new DataOutputStream(obj1.getOutputStream());
String
str=din.readLine();
Process p=Runtime.getRuntime().exec(str);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Clientrpc.java
import java.io.*;
import java.net.*;
import java.util.*;
class Clientrpc
{
public static void main(String
args[])
{
try
{
BufferedReader
in=new BufferedReader(new InputStreamReader(System.in));
Socket
clsct=new Socket("127.0.0.1",139);
DataInputStream
din=new DataInputStream(clsct.getInputStream());
DataOutputStream dout=new DataOutputStream(clsct.getOutputStream());
System.out.println("Enter String");
String str=in.readLine();
dout.writeBytes(str+'\n');
clsct.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
Output
11. Implement a program to retrieve the
data for the specified URL.
URLDemo.java
import java.net.*;
import java.io.*;
public class URLDemo
{
public static void main(String [] args)
{
try
{
URL url = new
URL("http://www.amrood.com/index.htm?language=en#j2se");
System.out.println("URL is " + url.toString());
System.out.println("protocol is "
+
url.getProtocol());
System.out.println("authority is "
+
url.getAuthority());
System.out.println("file name is " + url.getFile());
System.out.println("host is " + url.getHost());
System.out.println("path is " + url.getPath());
System.out.println("port is " + url.getPort());
System.out.println("default port is "
+
url.getDefaultPort());
System.out.println("query is " + url.getQuery());
System.out.println("ref is " + url.getRef());
}catch(IOException e)
{
e.printStackTrace();
}
}}
Output
12. Write a Java program to check
whether the given DNS is found in the internet
or not.
DNSLookup.java
import javax.naming.directory.Attributes;
import
javax.naming.directory.DirContext;
import
javax.naming.directory.InitialDirContext;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Hashtable;
public class DNSLookup
{
public static void main(String args[])
{
String host = "google.com";
try
{
InetAddress inetAddress =
InetAddress.getByName(host);
System.out.println(inetAddress.getHostName() + " " +
inetAddress.getHostAddress());
Hashtable<String, String> env
= new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.dns.DnsContextFactory");
InitialDirContext iDirC = new
InitialDirContext(env);
Attributes attributes =
iDirC.getAttributes("dns:/"+inetAddress.getHostName());
NamingEnumeration<?>
attributeEnumeration = attributes.getAll();
System.out.println("");
while
(attributeEnumeration.hasMore())
{
System.out.println(""
+ attributeEnumeration.next());
}
attributeEnumeration.close();
}
catch (UnknownHostException exception)
{
System.err.println("ERROR:
Cannot access '" + host + "'");
}
catch (NamingException exception)
{
System.err.println("ERROR: No
DNS record for '" + host + "'");
exception.printStackTrace();
}
}
}
Output
13. Write a program to implement
multicasting.
SimpleMulticastSource.java
import java.io.*;
import java.net.*;
public class SimpleMulticastSource
{
public
static void main(String[] args)
{
try
{
DatagramSocket
s = new DatagramSocket(); // Create
socket
byte[]
line = new byte[100];
System.out.print("Enter
text to send: ");
int
len = System.in.read(line);
InetAddress
dest = InetAddress.getByName("224.0.0.1");
DatagramPacket
pkt = new DatagramPacket(line, len, dest, 16900);
s.send(pkt);
s.close();
}
catch
(Exception err)
{
System.err.println(err);
}
}
}
SimpleMulticastDestination.java
import java.io.*;
import java.net.*;
public class SimpleMulticastDestination
{
public
static void main(String[] args)
{
try
{
MulticastSocket
ms = new MulticastSocket(16900); //
Create socket
ms.joinGroup(InetAddress.getByName("224.0.0.1"));
String
msg;
do
{
byte[]
line = new byte[100];
DatagramPacket
pkt = new DatagramPacket(line, line.length);
ms.receive(pkt);
msg
= new String(pkt.getData());
System.out.println("From
"+pkt.getAddress()+":"+msg.trim());
}
while
( !msg.trim().equals("close") );
ms.close(); // Close
connection
}
catch
(Exception err)
{
System.err.println(err);
}
}
}
Output
14. Write a network program using HTTP
to print the document for the given URL.
ListFilesInDirectory.java
import java.io.File;
public class ListFilesInDirectory
{
private
static int allElementsCount = 0;
private
static int directoriesCount = 0;
public
static void main(String[] args) {
String
directoryPath = "d:/ns2lab";
System.out.println(directoryPath);
listDirectory(directoryPath);
System.out.println("\n-----------------------------------------------");
System.out.println("Directory
stats");
System.out.println("-----------------------------------------------");
System.out.println("Directories:
" + directoriesCount);
System.out.println("Files:
" + (allElementsCount - directoriesCount));
}
public
static void listDirectory(String directoryPath)
{
for
(String contents: new File(directoryPath).list())
{
allElementsCount++;
contents =
directoryPath+"/"+contents;
System.out.println(contents);
if
(new File(contents).isDirectory()) {
directoriesCount++;
listDirectory(contents);
}
} } }
Output
SECURITY CENTRIC EXERCISES:
1. Write a program to convert your
college name from plain text to cipher text using
Transposition cipher method of
encryption.
transposition.java
import java.io.*;
import java.util.*;
class transposition {
public static void main(String args[])
{
String originalKey = "";
char[] keyArray;
int [] keyPosition;
String plainText;
char[][] plainTextArray;
int [] invalidCol;
String cipherText="";
Scanner console = new
Scanner(System.in);
System.out.println("Enter a key of
length 7 chars");;
originalKey = console.nextLine();
keyArray = originalKey.toCharArray();
Arrays.sort(keyArray);
System.out.println("Key Array :");
int x;
for (x=0; x<7; x++){
System.out.print("["+keyArray[x]+"]");
}
System.out.println();
keyPosition = new int[7];
int i = 0;
for (char c:keyArray)
{
keyPosition[i++] =
originalKey.indexOf(c);
}
System.out.println("Key Position
Array :");
for (x=0; x<7; x++){
System.out.print("["+keyPosition[x]+"]");
}
System.out.println();
System.out.println("Enter plain
text :");
plainText = console.nextLine();
char [] text;
text = plainText.toCharArray();
System.out.println("Plain Text
Array :");
for (x=0; x<text.length; x++){
System.out.print("["+text[x]+"]");
}
System.out.println("\n-----------------");
int cols = 7;
int rows;
if(text.length % cols == 0)
rows = text.length/cols;
else
rows = text.length/cols + 1;
plainTextArray = new char[rows][cols];
invalidCol = new int[cols];
for(i=0;i<cols; i++)
invalidCol[i] = -1;
i = 0;
int k = 0;
int c = 0;
int j = 0;
while(i<rows)
{
for(j=0; j<cols; j++)
if(k<text.length)
plainTextArray[i][j] = text[k++];
else
invalidCol[c++]=j;
i++;
}
System.out.println("Invalid Column
Array :");
for(i=0; i<cols; i++)
System.out.print("["+invalidCol[i]+"]");
System.out.println();
System.out.println("Plain Text
Array :");
System.out.println();
for (i=0;i<rows;i++)
{
for (j=0;j<cols; j++)
System.out.print("["+plainTextArray[i][j]+"]");
System.out.println();
}
int found = 0;
int colPos;
for(j=0; j<cols; j++)
{
colPos = keyPosition[j];
Arrays.sort((invalidCol));
found = Arrays.binarySearch(invalidCol,
colPos);
if (found<0)
{
for(i=0;i<rows;i++)
cipherText += plainTextArray[i][colPos];
}
else
{
for(i=0;i<rows-1;i++)
cipherText += plainTextArray[i][colPos];
}
}
System.out.println("The encrypted text
is \n"+cipherText);
}
}
Output
2. Write a program to convert your name
from plain text to cipher text using the One
Time Pads method of encryption.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
public class onetimepad
{
public static void main(String[] args)
throws IOException
{
BufferedReader brobj = new
BufferedReader(new InputStreamReader(System.in));
System.out.println("This is the
One_Time_Pad Encyption...");
System.out.println("Enter the
Plaintext Msg : ");
String temp_msg = brobj.readLine();
System.out.println("Now Generating
the Random String : ");
String key = "";
Random randGen = new Random(); //Hint:
one time pad uses random key
for ( int i = 0; i <
temp_msg.length() ; i++)
{
int randInt = randGen.nextInt(26); //Why
nextInt(26)??
key = key + (char)(65 + randInt) ; //Why
65 + randInt ??
}
String cipherText = "";
String msg = temp_msg.toUpperCase();
for(int i = 0 ; i < msg.length() ;
i++ )
{
int temp = (msg.charAt(i) +
key.charAt(i)) ;
if(temp >= 155)
{
temp = temp - 90;
}
else
{
temp = temp - 64;
}
char tempChar = (char)temp;
cipherText = cipherText + tempChar ;
}
System.out.println("Encryption
Done.." + "\n" + "One Time Cipher is : " +
cipherText);
System.out.println("Now Storing the
Cipher and String to a Local File...");
FileWriter fr = new
FileWriter("c:/one_time.txt", true);
BufferedWriter br = new
BufferedWriter(fr);
br.write("Cipher is: " +
cipherText + " & " + "Key is: " + key );
br.write("\n");
br.close();
System.out.println("Done! Quitting
now...");
}
}
Output
3. Write a program to encrypt a
paragraph using the Data Encryption Standard
Algorithm.
DES.java
import java.io.*;
import java.security.*;
import javax.crypto.*;
import java.util.*;
public class DES {
public static void main(String args[])
{
try
{
Cipher desCipher =
Cipher.getInstance("DES");
KeyGenerator keygen =
KeyGenerator.getInstance("DES");
SecureRandom randomSeed = new
SecureRandom();
keygen.init(randomSeed);
Key deskey = keygen.generateKey();
int mode = Cipher.ENCRYPT_MODE;
desCipher.init(mode, deskey);
Scanner console = new
Scanner(System.in);
System.out.println("Enter a text
for encryption");
String plainText = console.nextLine();
String encryptedText =
crypt(desCipher,plainText);
System.out.println("The encrypted
text is " +encryptedText);
mode = Cipher.DECRYPT_MODE;
desCipher.init(mode, deskey);
String decryptedText =
crypt(desCipher,encryptedText);
System.out.println("The decrypted
text is "+decryptedText);
}
catch(GeneralSecurityException e)
{
System.out.println("Security
Exception :"+ e.getMessage());
}
}
public static String crypt(Cipher desCipher,
String in) throws GeneralSecurityException
{
int inSize = desCipher.getBlockSize();
byte[] inBytes = new byte[inSize];
inBytes = in.getBytes();
int outSize =
desCipher.getOutputSize(inSize);
byte[] outBytes = new byte[outSize];
outBytes = desCipher.doFinal(inBytes);
String out = new String(outBytes);
return out;
}
}
Output
4. Write a program to encrypt your
biodata using the Advanced Encryption Standard
Algorithm.
AES.JAVA
import java.io.*;
import java.security.*;
import javax.crypto.*;
import java.util.*;
public class AES {
public static void main(String args[])
{
try
{
Cipher aesCipher =
Cipher.getInstance("AES");
KeyGenerator keygen =
KeyGenerator.getInstance("AES");
SecureRandom randomSeed = new
SecureRandom();
keygen.init(randomSeed);
Key aeskey = keygen.generateKey();
int mode = Cipher.ENCRYPT_MODE;
aesCipher.init(mode, aeskey);
Scanner console = new
Scanner(System.in);
System.out.println("Enter a text
for encryption");
String plainText = console.nextLine();
String encryptedText =
crypt(aesCipher,plainText);
System.out.println("The encrypted
text is " +encryptedText);
mode = Cipher.DECRYPT_MODE;
aesCipher.init(mode, aeskey);
String decryptedText =
crypt(aesCipher,encryptedText);
System.out.println("The decrypted
text is "+decryptedText);
}
catch(GeneralSecurityException e)
{
System.out.println("Security
Exception :"+ e.getMessage());
}
}
public static String crypt(Cipher
aesCipher, String in) throws GeneralSecurityException
{
int inSize = aesCipher.getBlockSize();
byte[] inBytes = new byte[inSize];
inBytes = in.getBytes();
int outSize =
aesCipher.getOutputSize(inSize);
byte[] outBytes = new byte[outSize];
outBytes = aesCipher.doFinal(inBytes);
String out = new String(outBytes);
return out;
}
}
Output
5. Write a program to decrypt the
“Network Security” theory syllabus using the RSA
Algorithm.
RSA.java
import java.math.BigInteger;
import java.util.Random;
import java.io.*;
public
class RSA {
private BigInteger p;
private BigInteger q;
private BigInteger N;
private BigInteger phi;
private BigInteger e;
private BigInteger d;
private int bitlength = 1024;
private int blocksize = 256; //blocksize in byte
private Random r;
public RSA() {
r = new Random();
p = BigInteger.probablePrime(bitlength, r);
q = BigInteger.probablePrime(bitlength, r);
N = p.multiply(q);
phi =
p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
e =
BigInteger.probablePrime(bitlength/2, r);
while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 &&
e.compareTo(phi) < 0 ) {
e.add(BigInteger.ONE);
}
d
= e.modInverse(phi);
}
public RSA(BigInteger e, BigInteger d, BigInteger N) {
this.e = e;
this.d = d;
this.N = N;
}
public static void main (String[] args) throws IOException
{
RSA rsa = new RSA();
DataInputStream in=new
DataInputStream(System.in);
String teststring ;
System.out.println("Enter the plain text:");
teststring=in.readLine();
System.out.println("Encrypting String: " + teststring);
System.out.println("String in Bytes: " +
bytesToString(teststring.getBytes()));
// encrypt
byte[] encrypted = rsa.encrypt(teststring.getBytes());
System.out.println("Encrypted String in Bytes: " +
bytesToString(encrypted));
// decrypt
byte[] decrypted = rsa.decrypt(encrypted);
System.out.println("Decrypted String in Bytes: " + bytesToString(decrypted));
System.out.println("Decrypted String: " + new
String(decrypted));
}
private static String bytesToString(byte[] encrypted) {
String test = "";
for (byte b : encrypted) {
test += Byte.toString(b);
}
return test;
}
public byte[] encrypt(byte[] message) {
return (new BigInteger(message)).modPow(e, N).toByteArray();
}
public byte[] decrypt(byte[] message) {
return (new BigInteger(message)).modPow(d, N).toByteArray();
}
}
Output
6. Write a program that takes a binary
file as input and performs bit stuffing and
Cyclic Redundancy Check Computation.
BitStuff.java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
public class BitStuff {
private static final int SIZE = 128;
private byte[] buffer;
private String pattern;
public BitStuff()
{
pattern =
"101111111111111101111111110";
}
public void stuffBytes(String infile,
String outfile) throws Exception
{
try
{
FileInputStream in = new
FileInputStream(infile);
FileOutputStream out = new
FileOutputStream(outfile);
buffer = new byte[SIZE];
int noBytes = in.read(buffer);
while(noBytes>0)
{
out.write(buffer);
out.write(pattern.getBytes());
buffer = new byte[SIZE];
noBytes = in.read(buffer);
}
out.close();
in.close();
}
catch(IOException ioe)
{
System.out.println("File io
problem");
ioe.printStackTrace();
}
}
public static void main(String[] args)
throws Exception {
Scanner console = new Scanner(System.in);
System.out.println("Enter the
filename to be bit stuffed");
String infile = console.nextLine();
System.out.println("Enter the
output filename");
String outfile = console.nextLine();
BitStuff stuffer = new BitStuff();
stuffer.stuffBytes(infile, outfile);
}
}
Output
7. Write a program to Simulate the
working of Sliding-Window protocol.
slider.java
import java.io.*;
import java.net.*;
public class slider
{
public static void main(String
a[])throws IOException
{
byte msg[]=new byte[200];
Socket s=new
Socket(InetAddress.getLocalHost(),2000);
DataInputStream in=new
DataInputStream(s.getInputStream());
DataInputStream ain=new
DataInputStream(System.in);
PrintStream p=new
PrintStream(s.getOutputStream());
char ch;
int i=0,ws=5;
while(true)
{
String str,astr;
int j=0;
i=0;
str=in.readLine();
if(str.equals("STOP"))
System.exit(0);
j=Integer.parseInt(str);
for(i=0;i<=j;i++)
{
str=in.readLine();
System.out.println(str);
if((i+1)%ws==0)
{
System.out.print("Give the
acknowledgement by press\"Enter\"key");
astr=ain.readLine();
p.println((i+1)+"ack");
}
}
if((i%ws)!=0)
{
System.out.print("Give the ack by
pres\"Enter\"key");
astr=ain.readLine();
p.println(i+"ack");
}
System.out.println("All data are
received and ack");
}
}
}
slides.java
import java.io.*;
import java.net.*;
public class slides
{
public static void main(String
a[])throws IOException
{
byte msg[]=new byte[200];
ServerSocket ser=new ServerSocket(2000);
Socket s;
PrintStream pout;
DataInputStream in=new
DataInputStream(System.in);
int start,end,l,j=0,i,ws=5,k=0;
String st,st1[]=new String[100];
System.out.println("Type\"STOP\"to
exit");
s=ser.accept();
pout=new
PrintStream(s.getOutputStream());
DataInputStream rin=new
DataInputStream(s.getInputStream());
System.out.println("Enter the data
to be send");
while(true)
{
st=in.readLine();
l=st.length();
start=0;
end=10;
j=0;
if(st.equals("STOP"))
{
pout.println(st);
break;
}
if(l<10)
{
st1[j++]=l+st;
}
else
{
for(i=l,j=0;i>0;i=i-10,j++)
{
st1[j]=(j+1)+st.substring(start,end);
start=end;
end=end+10;
if(end>l)
{
end=(start-10)+i;
}
}
System.out.println("Total no of
packets"+j);
}
pout.println(j);
for(i=0;i<=j;i++)
{
pout.println(st1[i]);
if((i+l)%ws==0)
{
System.out.println(rin.readLine());
}
}
if(i%ws!=0)
System.out.println(rin.readLine());
System.out.println("Enter the next
data to be send");
}
}
}
Output
8. Write a program to find the shortest
path in a network using Dijkstra's Algorithm.
Dijkstra.java
import java.io.*;
import java.util.*;
class Graph {
private static final int MAXNODES = 50;
private static final int INFINITY =
Integer.MAX_VALUE;
int n;
int[][] weight = new
int[MAXNODES][MAXNODES];
int[] distance = new int[MAXNODES];
int[] precede = new int[MAXNODES];
void buildSpanningTree(int source, int
destination) {
boolean[] visit = new boolean[MAXNODES];
for (int i=0 ; i<n ; i++) {
distance[i] = INFINITY;
precede[i] = INFINITY;
}
distance[source] = 0;
int current = source;
while (current != destination) {
int distcurr = distance[current];
int smalldist = INFINITY;
int k = -1;
visit[current] = true;
for (int i=0; i<n; i++) {
if (visit[i])
continue;
int newdist = distcurr +
weight[current][i];
if (newdist < distance[i]) {
distance[i] = newdist;
precede[i] = current;
}
if (distance[i] < smalldist) {
smalldist = distance[i];
k = i;
}
}
current = k;
}
}
int[] getShortestPath(int source, int
destination) {
int i = destination;
int finall = 0;
int[] path = new int[MAXNODES];
path[finall] = destination;
finall++;
while (precede[i] != source) {
i = precede[i];
path[finall] = i;
finall++;
}
path[finall] = source;
int[] result = new int[finall+1];
System.arraycopy(path, 0, result, 0,
finall+1);
return result;
}
void displayResult(int[] path) {
System.out.println("\nThe shortest
path followed is : \n");
for (int i = path.length-1 ; i>0 ;
i--)
System.out.println("\t\t( " +
path[i] + " ->" + path[i-1] +
" ) with cost = " +
weight[path[i]][path[i-1]]);
System.out.println("For the Total
Cost = " +
distance[path[path.length-1]]);
}
int getNumber(String msg) {
int ne = 0;
BufferedReader in = new
BufferedReader(new InputStreamReader(System.in));
try {
System.out.print("\n" + msg +
" : ");
ne = Integer.parseInt(in.readLine());
} catch (Exception e) {
System.out.println("I/O
Error");
}
return ne;
}
void SPA() {
n = getNumber("Enter the number of
nodes (Less than " + MAXNODES +
") in the matrix");
System.out.print("\nEnter the cost
matrix : \n\n");
for (int i=0 ; i<n ; i++)
for (int j=0 ; j<n ; j++)
weight[i][j] = getNumber("Cost
" + (i+1) + "--" + (j+1));
int s = getNumber("Enter the source
node");
int d = getNumber("Enter the
destination node");
buildSpanningTree(s, d);
displayResult(getShortestPath(s, d));
}
}
public class Dijkstra {
public static void main(String args[]) {
Graph g = new Graph();
g.SPA();
}
}
Output
9. Write a program to implement the
Token Bucket Algorithm for Congestion Control.
leaky.java
import java.util.*;
public class leaky
{
public static void main(String[] args)
{
Scanner my = new Scanner(System.in);
int no_groups,bucket_size;
System.out.print("\n Enter the bucket size : \t");
bucket_size = my.nextInt();
System.out.print("\n Enter the no of groups : \t");
no_groups = my.nextInt();
int no_packets[] = new int[no_groups];
int in_bw[] = new int[no_groups];
int out_bw,reqd_bw=0,tot_packets=0;
for(int i=0;i<no_groups;i++)
{
System.out.print("\n Enter the
no of packets for group " + (i+1) + "\t");
no_packets[i] = my.nextInt();
System.out.print("\n Enter the
input bandwidth for the group " + (i+1) + "\t");
in_bw[i] = my.nextInt();
if((tot_packets+no_packets[i])<=bucket_size)
{
tot_packets += no_packets[i];
}
else
{
do
{
System.out.println("
Bucket Overflow ");
System.out.println(" Enter
value less than " + (bucket_size-tot_packets));
no_packets[i] = my.nextInt();
}while((tot_packets+no_packets[i])>bucket_size);
tot_packets += no_packets[i];
}
reqd_bw +=
(no_packets[i]*in_bw[i]);
}
System.out.println("\nThe total required bandwidth is " +
reqd_bw);
System.out.println("Enter the output bandwidth ");
out_bw = my.nextInt();
int temp=reqd_bw;
int rem_pkts = tot_packets;
while((out_bw<=temp)&&(rem_pkts>0))
{
System.out.println("Data Sent
\n" + (--rem_pkts) + " packets remaining");
System.out.println("Remaining
Bandwidth " + (temp -= out_bw));
if((out_bw>temp)&&(rem_pkts>0))
System.out.println(rem_pkts +
" packet(s) discarded due to insufficient bandwidth");
}
}
}
Output
10. Write a program for the following
chat application.
One to One : Open a Socket connection
and display what is written by one to another.
ServerChat.java
import java.awt.*;
import java.net.*;
import javax.swing.*;
import java.awt.event.*;
class ServerChat extends JFrame
implements Runnable,ActionListener
{
TextArea msgArea;
Thread recieveThread;
TextField msgText;
Button sendButton;
DatagramSocket ds;
int cport=10,sport=11;
ServerChat() throws Exception
{
msgArea=new TextArea(10,10);
msgText=new TextField(10);
sendButton=new Button("send");
setLayout(new
FlowLayout(FlowLayout.CENTER));
add(msgArea);
add(msgText);
add(sendButton);
sendButton.addActionListener(this);
setBounds(10,10,200,200);
setVisible(true);
ds=new DatagramSocket(sport);
recieveThread=new Thread(this);
recieveThread.start();
}
public void actionPerformed(ActionEvent
e)
{
try
{
String message=msgText.getText();
DatagramPacket dp=new DatagramPacket(message.getBytes(),message.length(),InetAddress.getLocalHost(),cport);
ds.send(dp);
msgArea.append("You:"+message+"\n");
}catch(Exception e1){}
}
public void run()
{
byte b[]=new byte[1000];
while(true)
{
try
{
DatagramPacket dp=new
DatagramPacket(b,b.length);
ds.receive(dp);
String data=new
String(dp.getData(),0,dp.getLength());
msgArea.append("Client:"+data+"\n");
}catch(Exception e){}
}
}
public static void main(String x[])
throws Exception
{
new ServerChat(); } }
Clientchat.java
import java.awt.*;
import java.net.*;
import javax.swing.*;
import java.awt.event.*;
class ClientChat extends JFrame
implements Runnable,ActionListener
{
TextArea msgArea;
Thread recieveThread;
TextField msgText;
Button sendButton;
DatagramSocket ds;
int cport=10,sport=11;
ClientChat() throws Exception
{
msgArea=new TextArea(10,10);
msgText=new TextField(10);
sendButton=new Button("send");
setLayout(new
FlowLayout(FlowLayout.CENTER));
add(msgArea);
add(msgText);
add(sendButton);
sendButton.addActionListener(this);
setBounds(10,10,200,200);
setVisible(true);
ds=new DatagramSocket(cport);
recieveThread=new Thread(this);
recieveThread.start();
}
public void actionPerformed(ActionEvent
e)
{
try
{
String message=msgText.getText();
DatagramPacket dp=new
DatagramPacket(message.getBytes(),message.length(),InetAddress.getLocalHost(),sport);
ds.send(dp);
msgArea.append("You:"+message+"\n");
}catch(Exception e1){}
}
public void run()
{
byte b[]=new byte[1000];
while(true)
{
try
{
DatagramPacket dp=new
DatagramPacket(b,b.length);
ds.receive(dp);
String data=new
String(dp.getData(),0,dp.getLength());
msgArea.append("Server:"+data+"\n");
}catch(Exception e){}
}
}
public static void main(String x[])
throws Exception
{
new ClientChat();
}}
Output
Many to Many : Each Client Opens a Socket
connection to the client server and writes
to the socket. Whatever is written by
one can be seen by all.
Server.java
import java.io.*;
import java.net.*;
import java.util.*;
public class Server{
public static void main(String args[]) {
List<clientThread> t= new
ArrayList<clientThread>();
Socket clientSocket = null;
ServerSocket serverSocket = null;
int port_number=1111;
try {
serverSocket = new ServerSocket(port_number);
}
catch (IOException e)
{System.out.println(e);}
while(true){
try {
clientSocket = serverSocket.accept();
clientThread th=new
clientThread(clientSocket,t);
t.add(th);
th.start();
}
catch (IOException e) {
System.out.println(e);}
}
}
}
class clientThread extends Thread{
DataInputStream is = null;
String line;
String destClient="";
String name;
PrintStream os = null;
Socket clientSocket = null;
List<clientThread> t;
String clientIdentity;
public clientThread(Socket clientSocket, List<clientThread> t){
this.clientSocket=clientSocket;
this.t=t;
}
public void selectDestClient() throws IOException
{
int h=0;
os.println("\nTotal Members online
in Chat room : "+t.size());
os.println("\nWith whom you want to chat ?");
if(t.size()>1)
{
for(int i=0; i<t.size(); i++)
{
if(t.get(i)!=this)
{
this.os.println((++h)+" ) -
"+(t.get(i)).clientIdentity);
}
if(t.indexOf(t.get(i))==(t.size()-1))
{
os.println("\nPlease Enter the name
from above list to chat : ");
wh:while(true)
{
destClient=is.readLine();
for(clientThread ct:t)
{
if(destClient.equalsIgnoreCase(ct.clientIdentity)
&& ct!=t)//!destClient.equalsIgnoreCase(clientIdentity))
{
os.println("\nYou are connected
with "+destClient+"....Start enoying this chat
service.\n\n_______________________________________________________________________\n");
return;
}
}
os.println("\nInvalid destination.
--- There is NO user with name "+destClient+". \n\nPlease Re-enter :
");
continue;
}//wh:while
}
}
}else
{
this.os.println("\n- Currently
no other client has logged in for Chatting.\n- You are the first one.Wait for some clients....");
}
}
public void run()
{
try{
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
os.println("Enter your name.");
name = is.readLine();
clientIdentity=name;
os.println("\n\nWelcome "+name+" to this chatting
Application.\n\nInstructions :\n- To Sign-Out enter /quit in a new line\n- To
view List of Chat Members enter /view amd follow the instructions.\n\n");
for(int i=0;
i<t.size(); i++)
{
if(t.get(i)!=this)
{
(t.get(i)).os.println("*** A new user "+name+" entered
the chat room ***\n\n");
}
}
selectDestClient();
while (true) {
line = is.readLine();
if(line.startsWith("/view"))
{
selectDestClient();
continue;
}
if(line.startsWith("/quit")) break;
if(t.size()>1)
{
for(int i=0; i<t.size(); i++)
{
if((t.get(i))!=this)
{
if((t.get(i)).clientIdentity.equalsIgnoreCase(destClient))
{
(t.get(i)).os.println("\n\n<From
"+this.clientIdentity+"> "+line);
break;
}
}
}
}
}
if(t.size()>1)
{
for(int i=0; i<t.size(); i++)
{
if(t.get(i)!=this)
(t.get(i)).os.println("*** The user "+name+" left the
chat room***" );
}
}
os.println("*** Bye "+name+" ***");
t.remove(this);
is.close();
os.close();
clientSocket.close();
}
catch(IOException e){};
}
}
Client.java
import java.io.*;
import java.net.*;
public class Client implements Runnable{
static Socket clientSocket = null;
static PrintStream os = null;
static DataInputStream is = null;
static BufferedReader inputLine = null;
static boolean closed = false;
public static void main(String[] args) {
int port_number=1111;
String host="localhost";
try {
clientSocket = new Socket(host,
port_number);
inputLine = new BufferedReader(new
InputStreamReader(System.in));
os = new PrintStream(clientSocket.getOutputStream());
is = new
DataInputStream(clientSocket.getInputStream());
} catch (Exception e) {
System.err.println("Exception
occurred : "+e.getMessage());
}
if (clientSocket != null && os != null && is != null) {
try {
new Thread(new
Client()).start();
while (!closed) {
os.println(inputLine.readLine());
}
os.close();
is.close();
clientSocket.close();
} catch (IOException e) {
System.err.println("IOException:
" + e);
}
}
}
public void run() {
String responseLine;
try{
while ((responseLine = is.readLine()) != null) {
System.out.println(responseLine);
if (responseLine.indexOf("*** Bye") != -1) break;
}
closed=true;
} catch (IOException e) {
System.err.println("IOException:
" + e);
}
}}
Output
Comments
Post a Comment