SlideShare a Scribd company logo
1 of 22
Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur
CHHATTISGARH SWAMI VIVEKANAND TECHNICAL UNIVERSITY,
BHILAI (C.G.)
Semester: VIII Branch: Computer Science & Engg.
Subject: Network Securities Lab Practical Code: 322822 (22)
Total Practical Periods: 40
Total Marks in End Semester Exam: 40.
List of Experiments to be performed:
1. Networking Security Programming with TCP/IP for Application layer, Transport layer,
Network layer, Datalink layer protocols.
2. Socket Security Programming for address structures, byte manipulation & address
conversion functions, elementary socket system calls.
3. APIs security Programming for windows socket API, window socket & blocking I/O
model, blocking sockets, blocking functions, timeouts for blocking I/O.
4. Web Security Programming for firewall and others.
5. Web databases security programming.
6. Component Security Programming for CORBA.
7. CGI Security programming and Firewall
8. Programming for Cryptography and Digital Signature.
9. Java network Security programming.
10. Client Server Security Programming.
Recommended Books:-
1. Steven.W.R: UNIX Network Programming, PHI (VOL I& II)
2. Window Socket Programming by Bobb Quinn and Dave Schutes
3. Davis.R.: Windows Network Programming, Addison Wesley
CSE/8th
/NS Lab/Prepared by Vivek Kumar Sinha
Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur
EXPERIMENT NO. 01
Aim: Networking Security Programming with TCP/IP for Application layer,
Transport layer, Network layer, Datalink layer protocols
Program:-
import java.io.*;
public class
{
public static void main(String args[])
{
int sd[MAX_SOCKS]; /* one per TCP/IPv6, UDP/IPv6, TCP/IP, UDP/IP */
char *port, *addr = NULL;
struct addrinfo *res, hints;
port = argv[1]; /* port number as a string – must not be NULL */
if(argc == 3) addr = argv[2]; /* hostname – NULL implies ANY address */
memset(&hints, '0', sizeof(hints));
hints.ai_flags = AI_PASSIVE; /* if usrreq.addr NULL, sets sockaddr to ANY */
err = getaddrinfo(usrreq.addr, usrreq.port, &hints, &res);
if(err) { if(err == EAI_SYSTEM) perror("getaddrinfo");
else printf("getaddrinfo error %d - %s", err, gai_strerror(err)); return 1;
}
i = 0;
for(aip = res; aip; aip = aip->ai_next)
{
if(aip->ai_family != AF_INET && aip->ai_family != AF_INET6) continue; /*
create a socket for this protocol */
sd[i] = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if(sd[i] < 0)
{perror("socket");
return sd[i];
}
CSE/8th
/NS Lab/Prepared by Vivek Kumar Sinha
Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur
err = socket_options(sd[i], aip); /* set SO_REUSEADDR, SO_REUSPORT etc. */
if(err == -1) {perror("socket_options");
return 1;
}
err = bind(sd[i], res->ai_addr, res->ai_addrlen);
if(err == -1) {perror("bind"); return 1;
} /** perform other per-socket work here – e.g. maybe create threads etc **/
if(i == NUM_ELT(sd)) {printf("Insufficient socket elementsn");
break;
}
i++;
}
CSE/8th
/NS Lab/Prepared by Vivek Kumar Sinha
Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur
EXPERIMENT NO. 02
Aim: Socket Security Programming for address structures, byte manipulation &
address conversion functions, elementary socket system calls.
Program:-
import java.net.*;
public class host
{
socket address structure:
sockaddr_instruct in_addr
{
in_addr_t s_addr; /* 32-bit IPv4 address */ /* network byte ordered */
};
struct sockaddr_in { uint8_t sin_len; /* length of structure (16) */
sa_family_t sin_family; /* AF_INET */
in_port_t sin_port; /* 16-bit TCP or UDP port number */ /* network byte ordered */
struct in_addr sin_addr; /* 32-bit IPv4 address */ /* network byte ordered */ char
sin_zero[8]; /* unused */
};
int main(int argc, char *argv[])
{
int sockfd, numbytes;
char buf[MAXDATASIZE];
struct addrinfo hints, *servinfo, *p;
int rv;
char s[INET6_ADDRSTRLEN];
if (argc != 2) {
fprintf(stderr,"usage: client hostnamen");
exit(1);
}
CSE/8th
/NS Lab/Prepared by Vivek Kumar Sinha
Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo(argv[1], PORT, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %sn", gai_strerror(rv));
return 1;
}
// loop through all the results and connect to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("client: socket");
continue;
}
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("client: connect");
continue;
}
CSE/8th
/NS Lab/Prepared by Vivek Kumar Sinha
Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur
EXPERIMENT NO. 03
Aim : APIs security Programming for windows socket API, window socket &
blocking I/O model, blocking sockets, blocking functions, timeouts for blocking I/O.
Program:-
import java.net.*;
public class test
{
public static void main(String args[])
{
// Create a non-blocking socket and check for connections
try {
// Create a non-blocking socket channel on port 8080
SocketChannel sChannel = createSocketChannel("www.xxx", 8080);
// Before the socket is usable, the connection must be completed
// by calling finishConnect(), which is non-blocking
while (!sChannel.finishConnect()) {
// Do something else
System.out.println("wonderful");
}
// Socket channel is now ready to use
}
catch (IOException e) {
}
}
// Creates a non-blocking socket channel for the specified host name and port.
// connect() is called on the new channel before it is returned.
public static SocketChannel createSocketChannel(String hostName, int port) throws
IOException
{
// Create a non-blocking socket channel
SocketChannel sChannel = SocketChannel.open();
sChannel.configureBlocking(false);
// Send a connection request to the server; this method is non-blocking
sChannel.connect(new InetSocketAddress(hostName, port));
return sChannel;
}
}
CSE/8th
/NS Lab/Prepared by Vivek Kumar Sinha
Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur
EXPERIMENT NO. 04
Aim: Web Security Programming for firewall and others.
Program:-
import java.net.*;
import java.io.*;
public class
{
public static void main(String args[])
{
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
ServerSocket ss=new ServerSocket(2345);
Socket skt=ss.accept( );
BufferedReader skt_in=new BufferedReader(new
InputStreamReader(skt.getInputStream( )));
PrintStream skt_out=new PrintStream(skt.getOutputStream( ));
while(true)
{
System.out.println(skt_in.readLine( ));
skt_out.println(“What is your name”);
yourname=skt_in.readLine( );
System.out.println(yourname);
String s=skt_in.readLine( );
System.out.println(s);
String myname=br.readLine( );
skt_out.println(myname);
break;
}
while(true)
{
String recv=skt_in.readLine( );
System.out.println(yourname+”:”+recv);
String send=br.readLine( );
skt_out.println(send);
}
}
catch(Exception e)
{
System.out.println(“Exception :”+e);
} }
CSE/8th
/NS Lab/Prepared by Vivek Kumar Sinha
Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur
import java.net.*;
import java.io.*;
public class ChatClient
{
public static void main(String args[])
{
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
Socket skt=new Socket(“rungtaibm”,2345);
BufferedReader skt_in=new BufferedReader(new
InputStreamReader(skt.getInputStream( )));
PrintStream skt_out=new PrintStream(skt.getOutputStream( ));
while(true)
{
skt_out.println(“hello can I connect”);
skt_out.println(skt_in.readLine( ));
String myname=br.readLine( );
skt_out.println(myname);
skt_out.println(“What is yours”);
String yourname=skt_in.readLine( );
System.out.println(yourname);
break;
}
while(true)
{
String send=br.readLine( );
skt_out.println(send);
String recv=skt_in.readLine( );
System.out.println(yourname +”:”+recv);
}
}
catch(Exception e)
{
System.out.println(“Exception :”+e);
}
}
}
CSE/8th
/NS Lab/Prepared by Vivek Kumar Sinha
Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur
EXPERIMENT NO. 05
Aim: Component Security Programming for CORBA.
Program:-
package cs652.corba.server;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;
import org.omg.PortableServer.*;
public class HelloWorldServer {
public static void main(String[] args) {
try{
// create and initialize the ORB
ORB orb = ORB.init(args, null);
// get reference to rootpoa & activate the POAManager
POA rootpoa =
POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
rootpoa.the_POAManager().activate();
// create servant and get the CORBA reference of it
HelloWorldServiceImpl helloWorldImpl = new HelloWorldServiceImpl();
org.omg.CORBA.Object ref =
rootpoa.servant_to_reference(helloWorldImpl);
HelloWorldService helloWorldService =
HelloWorldServiceHelper.narrow(ref);
// get the root naming context and narrow it to the NamingContextExt object
org.omg.CORBA.Object objRef =
orb.resolve_initial_references("NameService");
NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);
// bind the Object Reference in Naming
NameComponent path[] = ncRef.to_name("HelloWorldService");
ncRef.rebind(path, helloWorldService);
// wait for invocations from clients
orb.run();
} catch (Exception e) {}
}
}
CSE/8th
/NS Lab/Prepared by Vivek Kumar Sinha
Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur
EXPERIMENT NO. 06
Aim: Programming for Cryptography and Digital Signature.
Program:-
PublicKeyCryptography
import java.security.*;
import java.security.cert.*;
import javax.crypto.*;
import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;
public class PublicKeyCryptography {
public static void main(String[] args) {
SymmetricEncrypt encryptUtil = new SymmetricEncrypt();
String strDataToEncrypt = "Hello World";
byte[] byteDataToTransmit = strDataToEncrypt.getBytes();
// Generating a SecretKey for Symmetric Encryption
SecretKey senderSecretKey = SymmetricEncrypt.getSecret();
//1. Encrypt the data using a Symmetric Key
byte[] byteCipherText =
encryptUtil.encryptData(byteDataToTransmit,senderSecretKey,"AES");
String strCipherText = new BASE64Encoder().encode(byteCipherText);
//2. Encrypt the Symmetric key using the Receivers public key
try{
// 2.1 Specify the Keystore where the Receivers certificate has been
imported
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
char [] password = "testpwd".toCharArray();
java.io.FileInputStream fis = new
java.io.FileInputStream("/home/Joebi/workspace/OWASP_Crypto/org/owasp/crypto/test
keystore.ks");
ks.load(fis, password);
fis.close();
// 2.2 Creating an X509 Certificate of the Receiver
X509Certificate recvcert ;
CSE/8th
/NS Lab/Prepared by Vivek Kumar Sinha
Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur
MessageDigest md = MessageDigest.getInstance("MD5");
recvcert = (X509Certificate)ks.getCertificate("testrecv");
// 2.3 Getting the Receivers public Key from the Certificate
PublicKey pubKeyReceiver = recvcert.getPublicKey();
// 2.4 Encrypting the SecretKey with the Receivers public Key
byte[] byteEncryptWithPublicKey =
encryptUtil.encryptData(senderSecretKey.getEncoded(),pubKeyReceiver,"RSA/ECB/PK
CS1Padding");
String strSenbyteEncryptWithPublicKey = new
BASE64Encoder().encode(byteEncryptWithPublicKey);
// 3. Create a Message Digest of the Data to be transmitted
md.update(byteDataToTransmit);
byte byteMDofDataToTransmit[] = md.digest();
String strMDofDataToTransmit = new String();
for (int i = 0; i < byteMDofDataToTransmit.length; i++){
strMDofDataToTransmit = strMDofDataToTransmit +
Integer.toHexString((int)byteMDofDataToTransmit[i] & 0xFF) ;
}
// 3.1 Message to be Signed = Encrypted Secret Key + MAC of the data to be
transmitted
String strMsgToSign = strSenbyteEncryptWithPublicKey + "|" +
strMDofDataToTransmit;
// 4. Sign the message
// 4.1 Get the private key of the Sender from the keystore by providing the password
set for the private key while creating the keys using keytool
char[] keypassword = "send123".toCharArray();
Key myKey = ks.getKey("testsender", keypassword);
PrivateKey myPrivateKey = (PrivateKey)myKey;
// 4.2 Sign the message
Signature mySign = Signature.getInstance("MD5withRSA");
mySign.initSign(myPrivateKey);
mySign.update(strMsgToSign.getBytes());
byte[] byteSignedData = mySign.sign();
// 5. The Values byteSignedData (the signature) and strMsgToSign (the data
which was signed) can be sent across to the receiver
// 6.Validate the Signature
// 6.1 Extracting the Senders public Key from his certificate
X509Certificate sendercert ;
CSE/8th
/NS Lab/Prepared by Vivek Kumar Sinha
Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur
sendercert = (X509Certificate)ks.getCertificate("testsender");
PublicKey pubKeySender = sendercert.getPublicKey();
// 6.2 Verifying the Signature
Signature myVerifySign = Signature.getInstance("MD5withRSA");
myVerifySign.initVerify(pubKeySender);
myVerifySign.update(strMsgToSign.getBytes());
boolean verifySign = myVerifySign.verify(byteSignedData);
if (verifySign == false)
{
System.out.println(" Error in validating Signature ");
}
else
System.out.println(" Successfully validated Signature ");
// 7. Decrypt the message using Recv private Key to get the Symmetric Key
char[] recvpassword = "recv123".toCharArray();
Key recvKey = ks.getKey("testrecv", recvpassword);
PrivateKey recvPrivateKey = (PrivateKey)recvKey;
// Parsing the MessageDigest and the encrypted value
String strRecvSignedData = new String (byteSignedData);
String[] strRecvSignedDataArray = new String [10];
strRecvSignedDataArray = strMsgToSign.split("|");
int intindexofsep = strMsgToSign.indexOf("|");
String strEncryptWithPublicKey = strMsgToSign.substring(0,intindexofsep);
String strHashOfData = strMsgToSign.substring(intindexofsep+1);
// Decrypting to get the symmetric key
byte[] bytestrEncryptWithPublicKey = new
BASE64Decoder().decodeBuffer(strEncryptWithPublicKey);
byte[] byteDecryptWithPrivateKey =
encryptUtil.decryptData(byteEncryptWithPublicKey,recvPrivateKey,"RSA/ECB/PKCS1
Padding");
// 8. Decrypt the data using the Symmetric Key
javax.crypto.spec.SecretKeySpec secretKeySpecDecrypted = new
javax.crypto.spec.SecretKeySpec(byteDecryptWithPrivateKey,"AES");
byte[] byteDecryptText =
encryptUtil.decryptData(byteCipherText,secretKeySpecDecrypted,"AES");
String strDecryptedText = new String(byteDecryptText);
System.out.println(" Decrypted data is " +strDecryptedText);
// 9. Compute MessageDigest of data + Signed message
MessageDigest recvmd = MessageDigest.getInstance("MD5");
CSE/8th
/NS Lab/Prepared by Vivek Kumar Sinha
Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur
recvmd.update(byteDecryptText);
byte byteHashOfRecvSignedData[] = recvmd.digest();
String strHashOfRecvSignedData = new String();
for (int i = 0; i < byteHashOfRecvSignedData.length; i++){
strHashOfRecvSignedData = strHashOfRecvSignedData +
Integer.toHexString((int)byteHashOfRecvSignedData[i] & 0xFF) ;
}
// 10. Validate if the Message Digest of the Decrypted Text matches the
Message Digest of the Original Message
if (!strHashOfRecvSignedData.equals(strHashOfData))
{
System.out.println(" Message has been tampered ");
}
}
catch(Exception exp)
{
System.out.println(" Exception caught " + exp);
exp.printStackTrace()
CSE/8th
/NS Lab/Prepared by Vivek Kumar Sinha
Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur
EXPERIMENT NO. 07
Aim : Java network Security programming.
Program:-
SymmetricEncrypt
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.Cipher;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;
import java.security.InvalidAlgorithmParameterException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import sun.misc.BASE64Encoder;
public class SymmetricEncrypt {
String strDataToEncrypt = new String();
String strCipherText = new String();
String strDecryptedText = new String();
static KeyGenerator keyGen;
private static String strHexVal = "0123456789abcdef";
public static SecretKey getSecret(){
try{
keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128);
}
catch(Exception exp)
{
System.out.println(" Exception inside constructor "
+exp);
}
CSE/8th
/NS Lab/Prepared by Vivek Kumar Sinha
Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur
SecretKey secretKey = keyGen.generateKey();
return secretKey;
}
/**
* Step2. Create a Cipher by specifying the following parameters
* a. Algorithm name - here it is AES
*/
public byte[] encryptData(byte[] byteDataToEncrypt, Key secretKey,
String Algorithm) {
byte[] byteCipherText = new byte[200];
try {
Cipher aesCipher = Cipher.getInstance(Algorithm);
/**
* Step 3. Initialize the Cipher for Encryption
*/
if(Algorithm.equals("AES")){
aesCipher.init(Cipher.ENCRYPT_MODE,secretKey,aesCipher.getParameters());
}
else
if(Algorithm.equals("RSA/ECB/PKCS1Padding")){
aesCipher.init(Cipher.ENCRYPT_MODE,secretKey);
}
byteCipherText = aesCipher.doFinal(byteDataToEncrypt);
strCipherText = new BASE64Encoder().encode(byteCipherText);
}
catch (NoSuchAlgorithmException noSuchAlgo)
{
System.out.println(" No Such Algorithm exists " +
noSuchAlgo);
}
catch (NoSuchPaddingException noSuchPad)
{
CSE/8th
/NS Lab/Prepared by Vivek Kumar Sinha
Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur
System.out.println(" No Such Padding
exists " + noSuchPad);
}
catch (InvalidKeyException invalidKey)
{
System.out.println(" Invalid
Key " + invalidKey);
}
catch (BadPaddingException
badPadding)
{
System.out.println(" Bad
Padding " + badPadding);
}
catch (IllegalBlockSizeException
illegalBlockSize)
{
System.out.println(" Illegal
Block Size " + illegalBlockSize);
illegalBlockSize.printStackTrace();
}
catch (Exception exp)
{
exp.printStackTrace();
}
return byteCipherText;
}
public byte[] decryptData(byte[] byteCipherText, Key secretKey,
String Algorithm) {
byte[] byteDecryptedText = new byte[200];
try{
Cipher aesCipher = Cipher.getInstance(Algorithm);
if(Algorithm.equals("AES")){
aesCipher.init(Cipher.DECRYPT_MODE,secretKey,aesCipher.getParameters());
}
else if(Algorithm.equals("RSA/ECB/PKCS1Padding")){
CSE/8th
/NS Lab/Prepared by Vivek Kumar Sinha
Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur
aesCipher.init(Cipher.DECRYPT_MODE,secretKey);
}
byteDecryptedText = aesCipher.doFinal(byteCipherText);
strDecryptedText = new String(byteDecryptedText);
}
catch (NoSuchAlgorithmException noSuchAlgo)
{
System.out.println(" No Such Algorithm exists " +
noSuchAlgo);
}
catch (NoSuchPaddingException noSuchPad)
{
System.out.println(" No Such Padding exists " +
noSuchPad);
}
catch (InvalidKeyException invalidKey)
{
System.out.println(" Invalid Key " +
invalidKey);
invalidKey.printStackTrace();
}
catch (BadPaddingException badPadding)
{
System.out.println(" Bad Padding " +
badPadding);
badPadding.printStackTrace();
}
catch (IllegalBlockSizeException illegalBlockSize)
{
System.out.println(" Illegal Block Size "
+ illegalBlockSize);
illegalBlockSize.printStackTrace();
}
catch (InvalidAlgorithmParameterException
invalidParam)
{
System.out.println(" Invalid Parameter "
+ invalidParam);
}
CSE/8th
/NS Lab/Prepared by Vivek Kumar Sinha
Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur
return byteDecryptedText;
}
public static byte[] convertStringToByteArray(String strInput) {
strInput = strInput.toLowerCase();
byte[] byteConverted = new byte[(strInput.length() + 1) / 2];
int j = 0;
int interimVal;
int nibble = -1;
for (int i = 0; i < strInput.length(); ++i) {
interimVal =
strHexVal.indexOf(strInput.charAt(i));
if (interimVal >= 0) {
if (nibble < 0) {
nibble = interimVal;
} else {
byteConverted[j++] = (byte)
((nibble << 4) + interimVal);
nibble = -1;
}
}
}
if (nibble >= 0) {
byteConverted[j++] = (byte) (nibble << 4);
}
if (j < byteConverted.length) {
byte[] byteTemp = new byte[j];
System.arraycopy(byteConverted, 0, byteTemp, 0,
j);
byteConverted = byteTemp;
}
return byteConverted;
}
public static String convertByteArrayToString(byte[] block) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < block.length; ++i) {
buf.append(strHexVal.charAt((block[i] >>> 4) &
0xf));
buf.append(strHexVal.charAt(block[i] & 0xf));
}
return buf.toString();
}
CSE/8th
/NS Lab/Prepared by Vivek Kumar Sinha
Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur
EXPERIMENT NO. 08
Aim: Client Server Security Connection programming.
Program:-
class Main
{
public static void main(String[] args) {
new TCPServer().start();
new TCPClient().start();
}
}
class TCPClient extends Thread {
// Connection properties
private static final String HOST = "127.0.0.1";
private static final int PORT = 56565;
public void run() {
// Socket class used for TCP connections
Socket sock = null;
// I/O components
BufferedReader input = null;
BufferedWriter output = null;
try {
// Connect our socket to the server.
sock = new Socket(HOST, PORT);
// Use a BufferedReader to read data from the server.
input = new BufferedReader(new InputStreamReader(sock.getInputStream()));
// Use a BufferedWriter to send data to the server.
output = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
// Send some data to the server.
String toServer = "Are you there, Server?";
System.out.println("ToServer: " + toServer);
output.write(toServer);
output.newLine();
output.flush();
// Wait for a response from the server and display it.
CSE/8th
/NS Lab/Prepared by Vivek Kumar Sinha
Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur
String fromServer = input.readLine();
System.out.println("FromServer: " + fromServer);
} catch (final IOException ex) {
} finally {
// Do our best to ensure a clean close procedure.
// Closing the socket will also close input and output.
try {
if (sock != null) {
sock.close();
}
} catch (final IOException ex) {
}
}
}
}
class TCPServer extends Thread {
// Connection properties
private static final int PORT = 56565;
public void run() {
// ServerSocket class used to accept TCP connections
ServerSocket server = null;
Socket sock = null;
// I/O components
BufferedReader input = null;
BufferedWriter output = null;
try {
// Create our server on the given port.
server = new ServerSocket(PORT);
// Wait for a client to connect to us.
sock = server.accept();
// Use a BufferedReader to read data from the client.
input = new BufferedReader(new InputStreamReader(sock.getInputStream()));
// Use a BufferedWriter to send data to the client.
output = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
// Wait for the client to talk to us.
String fromClient = input.readLine();
CSE/8th
/NS Lab/Prepared by Vivek Kumar Sinha
Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur
System.out.println("FromClient: " + fromClient);
// Send them a response.
String toClient = "Yes, I'm here, Client.";
System.out.println("ToClient: " + toClient);
output.write(toClient);
output.newLine();
output.flush();
} catch (final IOException ex) {
} finally {
// Do our best to ensure a clean close procedure.
// Closing the socket will also close input and output.
try {
if (sock != null) {
sock.close();
}
} catch (final IOException ex) {
}
// Close the server socket, as well.
try {
if (server != null) {
server.close();
}
} catch (final IOException ex) {
}
}
}
}
CSE/8th
/NS Lab/Prepared by Vivek Kumar Sinha
Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur
CSE/8th
/NS Lab/Prepared by Vivek Kumar Sinha

More Related Content

What's hot

Cs423 raw sockets_bw
Cs423 raw sockets_bwCs423 raw sockets_bw
Cs423 raw sockets_bwjktjpc
 
Design and implementation_of_shellcodes
Design and implementation_of_shellcodesDesign and implementation_of_shellcodes
Design and implementation_of_shellcodesAmr Ali
 
Computer Networks Lab File
Computer Networks Lab FileComputer Networks Lab File
Computer Networks Lab FileKandarp Tiwari
 
[ZigBee 嵌入式系統] ZigBee 應用實作 - 使用 TI Z-Stack Firmware
[ZigBee 嵌入式系統] ZigBee 應用實作 - 使用 TI Z-Stack Firmware[ZigBee 嵌入式系統] ZigBee 應用實作 - 使用 TI Z-Stack Firmware
[ZigBee 嵌入式系統] ZigBee 應用實作 - 使用 TI Z-Stack FirmwareSimen Li
 
Cisco IOS shellcode: All-in-one
Cisco IOS shellcode: All-in-oneCisco IOS shellcode: All-in-one
Cisco IOS shellcode: All-in-oneDefconRussia
 
09 - ROP countermeasures, can we fix this?
09 - ROP countermeasures, can we fix this?09 - ROP countermeasures, can we fix this?
09 - ROP countermeasures, can we fix this?Alexandre Moneger
 
Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations DVClub
 
08 - Return Oriented Programming, the chosen one
08 - Return Oriented Programming, the chosen one08 - Return Oriented Programming, the chosen one
08 - Return Oriented Programming, the chosen oneAlexandre Moneger
 
[嵌入式系統] MCS-51 實驗 - 使用 IAR (2)
[嵌入式系統] MCS-51 實驗 - 使用 IAR (2)[嵌入式系統] MCS-51 實驗 - 使用 IAR (2)
[嵌入式系統] MCS-51 實驗 - 使用 IAR (2)Simen Li
 
Best Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' MistakesBest Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' MistakesAndrey Karpov
 
Bridge TensorFlow to run on Intel nGraph backends (v0.4)
Bridge TensorFlow to run on Intel nGraph backends (v0.4)Bridge TensorFlow to run on Intel nGraph backends (v0.4)
Bridge TensorFlow to run on Intel nGraph backends (v0.4)Mr. Vengineer
 
Network lab manual
Network lab manualNetwork lab manual
Network lab manualPrabhu D
 
Georgy Nosenko - An introduction to the use SMT solvers for software security
Georgy Nosenko - An introduction to the use SMT solvers for software securityGeorgy Nosenko - An introduction to the use SMT solvers for software security
Georgy Nosenko - An introduction to the use SMT solvers for software securityDefconRussia
 
Network lap pgms 7th semester
Network lap pgms 7th semesterNetwork lap pgms 7th semester
Network lap pgms 7th semesterDOSONKA Group
 
[嵌入式系統] MCS-51 實驗 - 使用 IAR (3)
[嵌入式系統] MCS-51 實驗 - 使用 IAR (3)[嵌入式系統] MCS-51 實驗 - 使用 IAR (3)
[嵌入式系統] MCS-51 實驗 - 使用 IAR (3)Simen Li
 
Java Bytecode Fundamentals - JUG.lv
Java Bytecode Fundamentals - JUG.lvJava Bytecode Fundamentals - JUG.lv
Java Bytecode Fundamentals - JUG.lvAnton Arhipov
 
[ROOTCON13] Pilot Study on Semi-Automated Patch Diffing by Applying Machine-L...
[ROOTCON13] Pilot Study on Semi-Automated Patch Diffing by Applying Machine-L...[ROOTCON13] Pilot Study on Semi-Automated Patch Diffing by Applying Machine-L...
[ROOTCON13] Pilot Study on Semi-Automated Patch Diffing by Applying Machine-L...Asuka Nakajima
 
C++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical ReviewerC++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical ReviewerAndrey Karpov
 
Advanced cfg bypass on adobe flash player 18 defcon russia 23
Advanced cfg bypass on adobe flash player 18 defcon russia 23Advanced cfg bypass on adobe flash player 18 defcon russia 23
Advanced cfg bypass on adobe flash player 18 defcon russia 23DefconRussia
 

What's hot (20)

Cs423 raw sockets_bw
Cs423 raw sockets_bwCs423 raw sockets_bw
Cs423 raw sockets_bw
 
Design and implementation_of_shellcodes
Design and implementation_of_shellcodesDesign and implementation_of_shellcodes
Design and implementation_of_shellcodes
 
Computer Networks Lab File
Computer Networks Lab FileComputer Networks Lab File
Computer Networks Lab File
 
[ZigBee 嵌入式系統] ZigBee 應用實作 - 使用 TI Z-Stack Firmware
[ZigBee 嵌入式系統] ZigBee 應用實作 - 使用 TI Z-Stack Firmware[ZigBee 嵌入式系統] ZigBee 應用實作 - 使用 TI Z-Stack Firmware
[ZigBee 嵌入式系統] ZigBee 應用實作 - 使用 TI Z-Stack Firmware
 
Cisco IOS shellcode: All-in-one
Cisco IOS shellcode: All-in-oneCisco IOS shellcode: All-in-one
Cisco IOS shellcode: All-in-one
 
09 - ROP countermeasures, can we fix this?
09 - ROP countermeasures, can we fix this?09 - ROP countermeasures, can we fix this?
09 - ROP countermeasures, can we fix this?
 
Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations
 
08 - Return Oriented Programming, the chosen one
08 - Return Oriented Programming, the chosen one08 - Return Oriented Programming, the chosen one
08 - Return Oriented Programming, the chosen one
 
[嵌入式系統] MCS-51 實驗 - 使用 IAR (2)
[嵌入式系統] MCS-51 實驗 - 使用 IAR (2)[嵌入式系統] MCS-51 實驗 - 使用 IAR (2)
[嵌入式系統] MCS-51 實驗 - 使用 IAR (2)
 
Best Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' MistakesBest Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' Mistakes
 
Bridge TensorFlow to run on Intel nGraph backends (v0.4)
Bridge TensorFlow to run on Intel nGraph backends (v0.4)Bridge TensorFlow to run on Intel nGraph backends (v0.4)
Bridge TensorFlow to run on Intel nGraph backends (v0.4)
 
Network lab manual
Network lab manualNetwork lab manual
Network lab manual
 
Georgy Nosenko - An introduction to the use SMT solvers for software security
Georgy Nosenko - An introduction to the use SMT solvers for software securityGeorgy Nosenko - An introduction to the use SMT solvers for software security
Georgy Nosenko - An introduction to the use SMT solvers for software security
 
Network lap pgms 7th semester
Network lap pgms 7th semesterNetwork lap pgms 7th semester
Network lap pgms 7th semester
 
[嵌入式系統] MCS-51 實驗 - 使用 IAR (3)
[嵌入式系統] MCS-51 實驗 - 使用 IAR (3)[嵌入式系統] MCS-51 實驗 - 使用 IAR (3)
[嵌入式系統] MCS-51 實驗 - 使用 IAR (3)
 
Java Bytecode Fundamentals - JUG.lv
Java Bytecode Fundamentals - JUG.lvJava Bytecode Fundamentals - JUG.lv
Java Bytecode Fundamentals - JUG.lv
 
[ROOTCON13] Pilot Study on Semi-Automated Patch Diffing by Applying Machine-L...
[ROOTCON13] Pilot Study on Semi-Automated Patch Diffing by Applying Machine-L...[ROOTCON13] Pilot Study on Semi-Automated Patch Diffing by Applying Machine-L...
[ROOTCON13] Pilot Study on Semi-Automated Patch Diffing by Applying Machine-L...
 
C++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical ReviewerC++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical Reviewer
 
Advanced cfg bypass on adobe flash player 18 defcon russia 23
Advanced cfg bypass on adobe flash player 18 defcon russia 23Advanced cfg bypass on adobe flash player 18 defcon russia 23
Advanced cfg bypass on adobe flash player 18 defcon russia 23
 
Codes
CodesCodes
Codes
 

Viewers also liked

IPE-UnipolSai"Osservatorio delle quotate:il bilancio UnipolSai 2014" 2015
IPE-UnipolSai"Osservatorio delle quotate:il bilancio UnipolSai 2014" 2015IPE-UnipolSai"Osservatorio delle quotate:il bilancio UnipolSai 2014" 2015
IPE-UnipolSai"Osservatorio delle quotate:il bilancio UnipolSai 2014" 2015IPE Business School
 
microprocessor 8086 lab manual !!
microprocessor 8086 lab manual !!microprocessor 8086 lab manual !!
microprocessor 8086 lab manual !!Sushil Mishra
 
PPT SISTEM PENCERNAAN
PPT SISTEM PENCERNAANPPT SISTEM PENCERNAAN
PPT SISTEM PENCERNAANghina_rahma
 

Viewers also liked (8)

OHM CAD SYSTEM Capabilities
OHM CAD SYSTEM CapabilitiesOHM CAD SYSTEM Capabilities
OHM CAD SYSTEM Capabilities
 
IPE-UnipolSai"Osservatorio delle quotate:il bilancio UnipolSai 2014" 2015
IPE-UnipolSai"Osservatorio delle quotate:il bilancio UnipolSai 2014" 2015IPE-UnipolSai"Osservatorio delle quotate:il bilancio UnipolSai 2014" 2015
IPE-UnipolSai"Osservatorio delle quotate:il bilancio UnipolSai 2014" 2015
 
Main ds manual
Main ds manualMain ds manual
Main ds manual
 
Npc13
Npc13Npc13
Npc13
 
Network Programming
Network ProgrammingNetwork Programming
Network Programming
 
Cse 7 softcomputing lab
Cse 7 softcomputing labCse 7 softcomputing lab
Cse 7 softcomputing lab
 
microprocessor 8086 lab manual !!
microprocessor 8086 lab manual !!microprocessor 8086 lab manual !!
microprocessor 8086 lab manual !!
 
PPT SISTEM PENCERNAAN
PPT SISTEM PENCERNAANPPT SISTEM PENCERNAAN
PPT SISTEM PENCERNAAN
 

Similar to Network Security Lab Experiments and Programming

Lab Assignment 4 CSE330 Spring 2014 Skeleton Code for ex.docx
 Lab Assignment 4 CSE330 Spring 2014  Skeleton Code for ex.docx Lab Assignment 4 CSE330 Spring 2014  Skeleton Code for ex.docx
Lab Assignment 4 CSE330 Spring 2014 Skeleton Code for ex.docxMARRY7
 
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Yandex
 
RMI Java Programming Lab Manual 2019
RMI Java Programming Lab Manual 2019RMI Java Programming Lab Manual 2019
RMI Java Programming Lab Manual 2019Gebreigziabher Ab
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the wayOleg Podsechin
 
Comunicação Android Arduino - JASI 2015
Comunicação Android Arduino - JASI 2015Comunicação Android Arduino - JASI 2015
Comunicação Android Arduino - JASI 2015Rodrigo Reis Alves
 
Networks lab
Networks labNetworks lab
Networks labsvijiiii
 
Networks lab
Networks labNetworks lab
Networks labsvijiiii
 
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 202010 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020Matt Raible
 
Udp socket programming(Florian)
Udp socket programming(Florian)Udp socket programming(Florian)
Udp socket programming(Florian)Flor Ian
 

Similar to Network Security Lab Experiments and Programming (20)

Computer networkppt4577
Computer networkppt4577Computer networkppt4577
Computer networkppt4577
 
Lab Assignment 4 CSE330 Spring 2014 Skeleton Code for ex.docx
 Lab Assignment 4 CSE330 Spring 2014  Skeleton Code for ex.docx Lab Assignment 4 CSE330 Spring 2014  Skeleton Code for ex.docx
Lab Assignment 4 CSE330 Spring 2014 Skeleton Code for ex.docx
 
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++
 
RMI Java Programming Lab Manual 2019
RMI Java Programming Lab Manual 2019RMI Java Programming Lab Manual 2019
RMI Java Programming Lab Manual 2019
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the way
 
Java final lab
Java final labJava final lab
Java final lab
 
Comunicação Android Arduino - JASI 2015
Comunicação Android Arduino - JASI 2015Comunicação Android Arduino - JASI 2015
Comunicação Android Arduino - JASI 2015
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Lab
LabLab
Lab
 
Python para equipos de ciberseguridad
Python para equipos de ciberseguridad Python para equipos de ciberseguridad
Python para equipos de ciberseguridad
 
Networks lab
Networks labNetworks lab
Networks lab
 
Networks lab
Networks labNetworks lab
Networks lab
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 202010 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
 
Learning Dtrace
Learning DtraceLearning Dtrace
Learning Dtrace
 
Os lab final
Os lab finalOs lab final
Os lab final
 
Pemrograman Jaringan
Pemrograman JaringanPemrograman Jaringan
Pemrograman Jaringan
 
Computer network
Computer networkComputer network
Computer network
 
分散式系統
分散式系統分散式系統
分散式系統
 
Udp socket programming(Florian)
Udp socket programming(Florian)Udp socket programming(Florian)
Udp socket programming(Florian)
 

More from Vivek Kumar Sinha (20)

Software engg unit 4
Software engg unit 4 Software engg unit 4
Software engg unit 4
 
Software engg unit 3
Software engg unit 3 Software engg unit 3
Software engg unit 3
 
Software engg unit 2
Software engg unit 2 Software engg unit 2
Software engg unit 2
 
Software engg unit 1
Software engg unit 1 Software engg unit 1
Software engg unit 1
 
Data structure
Data structureData structure
Data structure
 
Mathematics basics
Mathematics basicsMathematics basics
Mathematics basics
 
E commerce 5_units_notes
E commerce 5_units_notesE commerce 5_units_notes
E commerce 5_units_notes
 
B.ped
B.pedB.ped
B.ped
 
Subject distribution
Subject distributionSubject distribution
Subject distribution
 
Revision report final
Revision report finalRevision report final
Revision report final
 
Lession plan mis
Lession plan misLession plan mis
Lession plan mis
 
Lession plan dmw
Lession plan dmwLession plan dmw
Lession plan dmw
 
Faculty planning
Faculty planningFaculty planning
Faculty planning
 
Final presentation on computer network
Final presentation on computer networkFinal presentation on computer network
Final presentation on computer network
 
Np syllabus summary
Np syllabus summaryNp syllabus summary
Np syllabus summary
 
Internet of things
Internet of thingsInternet of things
Internet of things
 
Induction program 2017
Induction program 2017Induction program 2017
Induction program 2017
 
Vivek
VivekVivek
Vivek
 
E magzine et&amp;t
E magzine et&amp;tE magzine et&amp;t
E magzine et&amp;t
 
Mechanical engineering department (1)
Mechanical engineering department (1)Mechanical engineering department (1)
Mechanical engineering department (1)
 

Recently uploaded

College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...RajaP95
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxhumanexperienceaaa
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 

Recently uploaded (20)

College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 

Network Security Lab Experiments and Programming

  • 1. Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur CHHATTISGARH SWAMI VIVEKANAND TECHNICAL UNIVERSITY, BHILAI (C.G.) Semester: VIII Branch: Computer Science & Engg. Subject: Network Securities Lab Practical Code: 322822 (22) Total Practical Periods: 40 Total Marks in End Semester Exam: 40. List of Experiments to be performed: 1. Networking Security Programming with TCP/IP for Application layer, Transport layer, Network layer, Datalink layer protocols. 2. Socket Security Programming for address structures, byte manipulation & address conversion functions, elementary socket system calls. 3. APIs security Programming for windows socket API, window socket & blocking I/O model, blocking sockets, blocking functions, timeouts for blocking I/O. 4. Web Security Programming for firewall and others. 5. Web databases security programming. 6. Component Security Programming for CORBA. 7. CGI Security programming and Firewall 8. Programming for Cryptography and Digital Signature. 9. Java network Security programming. 10. Client Server Security Programming. Recommended Books:- 1. Steven.W.R: UNIX Network Programming, PHI (VOL I& II) 2. Window Socket Programming by Bobb Quinn and Dave Schutes 3. Davis.R.: Windows Network Programming, Addison Wesley CSE/8th /NS Lab/Prepared by Vivek Kumar Sinha
  • 2. Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur EXPERIMENT NO. 01 Aim: Networking Security Programming with TCP/IP for Application layer, Transport layer, Network layer, Datalink layer protocols Program:- import java.io.*; public class { public static void main(String args[]) { int sd[MAX_SOCKS]; /* one per TCP/IPv6, UDP/IPv6, TCP/IP, UDP/IP */ char *port, *addr = NULL; struct addrinfo *res, hints; port = argv[1]; /* port number as a string – must not be NULL */ if(argc == 3) addr = argv[2]; /* hostname – NULL implies ANY address */ memset(&hints, '0', sizeof(hints)); hints.ai_flags = AI_PASSIVE; /* if usrreq.addr NULL, sets sockaddr to ANY */ err = getaddrinfo(usrreq.addr, usrreq.port, &hints, &res); if(err) { if(err == EAI_SYSTEM) perror("getaddrinfo"); else printf("getaddrinfo error %d - %s", err, gai_strerror(err)); return 1; } i = 0; for(aip = res; aip; aip = aip->ai_next) { if(aip->ai_family != AF_INET && aip->ai_family != AF_INET6) continue; /* create a socket for this protocol */ sd[i] = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if(sd[i] < 0) {perror("socket"); return sd[i]; } CSE/8th /NS Lab/Prepared by Vivek Kumar Sinha
  • 3. Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur err = socket_options(sd[i], aip); /* set SO_REUSEADDR, SO_REUSPORT etc. */ if(err == -1) {perror("socket_options"); return 1; } err = bind(sd[i], res->ai_addr, res->ai_addrlen); if(err == -1) {perror("bind"); return 1; } /** perform other per-socket work here – e.g. maybe create threads etc **/ if(i == NUM_ELT(sd)) {printf("Insufficient socket elementsn"); break; } i++; } CSE/8th /NS Lab/Prepared by Vivek Kumar Sinha
  • 4. Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur EXPERIMENT NO. 02 Aim: Socket Security Programming for address structures, byte manipulation & address conversion functions, elementary socket system calls. Program:- import java.net.*; public class host { socket address structure: sockaddr_instruct in_addr { in_addr_t s_addr; /* 32-bit IPv4 address */ /* network byte ordered */ }; struct sockaddr_in { uint8_t sin_len; /* length of structure (16) */ sa_family_t sin_family; /* AF_INET */ in_port_t sin_port; /* 16-bit TCP or UDP port number */ /* network byte ordered */ struct in_addr sin_addr; /* 32-bit IPv4 address */ /* network byte ordered */ char sin_zero[8]; /* unused */ }; int main(int argc, char *argv[]) { int sockfd, numbytes; char buf[MAXDATASIZE]; struct addrinfo hints, *servinfo, *p; int rv; char s[INET6_ADDRSTRLEN]; if (argc != 2) { fprintf(stderr,"usage: client hostnamen"); exit(1); } CSE/8th /NS Lab/Prepared by Vivek Kumar Sinha
  • 5. Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ((rv = getaddrinfo(argv[1], PORT, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %sn", gai_strerror(rv)); return 1; } // loop through all the results and connect to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("client: socket"); continue; } if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("client: connect"); continue; } CSE/8th /NS Lab/Prepared by Vivek Kumar Sinha
  • 6. Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur EXPERIMENT NO. 03 Aim : APIs security Programming for windows socket API, window socket & blocking I/O model, blocking sockets, blocking functions, timeouts for blocking I/O. Program:- import java.net.*; public class test { public static void main(String args[]) { // Create a non-blocking socket and check for connections try { // Create a non-blocking socket channel on port 8080 SocketChannel sChannel = createSocketChannel("www.xxx", 8080); // Before the socket is usable, the connection must be completed // by calling finishConnect(), which is non-blocking while (!sChannel.finishConnect()) { // Do something else System.out.println("wonderful"); } // Socket channel is now ready to use } catch (IOException e) { } } // Creates a non-blocking socket channel for the specified host name and port. // connect() is called on the new channel before it is returned. public static SocketChannel createSocketChannel(String hostName, int port) throws IOException { // Create a non-blocking socket channel SocketChannel sChannel = SocketChannel.open(); sChannel.configureBlocking(false); // Send a connection request to the server; this method is non-blocking sChannel.connect(new InetSocketAddress(hostName, port)); return sChannel; } } CSE/8th /NS Lab/Prepared by Vivek Kumar Sinha
  • 7. Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur EXPERIMENT NO. 04 Aim: Web Security Programming for firewall and others. Program:- import java.net.*; import java.io.*; public class { public static void main(String args[]) { try { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); ServerSocket ss=new ServerSocket(2345); Socket skt=ss.accept( ); BufferedReader skt_in=new BufferedReader(new InputStreamReader(skt.getInputStream( ))); PrintStream skt_out=new PrintStream(skt.getOutputStream( )); while(true) { System.out.println(skt_in.readLine( )); skt_out.println(“What is your name”); yourname=skt_in.readLine( ); System.out.println(yourname); String s=skt_in.readLine( ); System.out.println(s); String myname=br.readLine( ); skt_out.println(myname); break; } while(true) { String recv=skt_in.readLine( ); System.out.println(yourname+”:”+recv); String send=br.readLine( ); skt_out.println(send); } } catch(Exception e) { System.out.println(“Exception :”+e); } } CSE/8th /NS Lab/Prepared by Vivek Kumar Sinha
  • 8. Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur import java.net.*; import java.io.*; public class ChatClient { public static void main(String args[]) { try { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); Socket skt=new Socket(“rungtaibm”,2345); BufferedReader skt_in=new BufferedReader(new InputStreamReader(skt.getInputStream( ))); PrintStream skt_out=new PrintStream(skt.getOutputStream( )); while(true) { skt_out.println(“hello can I connect”); skt_out.println(skt_in.readLine( )); String myname=br.readLine( ); skt_out.println(myname); skt_out.println(“What is yours”); String yourname=skt_in.readLine( ); System.out.println(yourname); break; } while(true) { String send=br.readLine( ); skt_out.println(send); String recv=skt_in.readLine( ); System.out.println(yourname +”:”+recv); } } catch(Exception e) { System.out.println(“Exception :”+e); } } } CSE/8th /NS Lab/Prepared by Vivek Kumar Sinha
  • 9. Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur EXPERIMENT NO. 05 Aim: Component Security Programming for CORBA. Program:- package cs652.corba.server; import org.omg.CosNaming.*; import org.omg.CosNaming.NamingContextPackage.*; import org.omg.CORBA.*; import org.omg.PortableServer.*; public class HelloWorldServer { public static void main(String[] args) { try{ // create and initialize the ORB ORB orb = ORB.init(args, null); // get reference to rootpoa & activate the POAManager POA rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA")); rootpoa.the_POAManager().activate(); // create servant and get the CORBA reference of it HelloWorldServiceImpl helloWorldImpl = new HelloWorldServiceImpl(); org.omg.CORBA.Object ref = rootpoa.servant_to_reference(helloWorldImpl); HelloWorldService helloWorldService = HelloWorldServiceHelper.narrow(ref); // get the root naming context and narrow it to the NamingContextExt object org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService"); NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef); // bind the Object Reference in Naming NameComponent path[] = ncRef.to_name("HelloWorldService"); ncRef.rebind(path, helloWorldService); // wait for invocations from clients orb.run(); } catch (Exception e) {} } } CSE/8th /NS Lab/Prepared by Vivek Kumar Sinha
  • 10. Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur EXPERIMENT NO. 06 Aim: Programming for Cryptography and Digital Signature. Program:- PublicKeyCryptography import java.security.*; import java.security.cert.*; import javax.crypto.*; import sun.misc.BASE64Encoder; import sun.misc.BASE64Decoder; public class PublicKeyCryptography { public static void main(String[] args) { SymmetricEncrypt encryptUtil = new SymmetricEncrypt(); String strDataToEncrypt = "Hello World"; byte[] byteDataToTransmit = strDataToEncrypt.getBytes(); // Generating a SecretKey for Symmetric Encryption SecretKey senderSecretKey = SymmetricEncrypt.getSecret(); //1. Encrypt the data using a Symmetric Key byte[] byteCipherText = encryptUtil.encryptData(byteDataToTransmit,senderSecretKey,"AES"); String strCipherText = new BASE64Encoder().encode(byteCipherText); //2. Encrypt the Symmetric key using the Receivers public key try{ // 2.1 Specify the Keystore where the Receivers certificate has been imported KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); char [] password = "testpwd".toCharArray(); java.io.FileInputStream fis = new java.io.FileInputStream("/home/Joebi/workspace/OWASP_Crypto/org/owasp/crypto/test keystore.ks"); ks.load(fis, password); fis.close(); // 2.2 Creating an X509 Certificate of the Receiver X509Certificate recvcert ; CSE/8th /NS Lab/Prepared by Vivek Kumar Sinha
  • 11. Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur MessageDigest md = MessageDigest.getInstance("MD5"); recvcert = (X509Certificate)ks.getCertificate("testrecv"); // 2.3 Getting the Receivers public Key from the Certificate PublicKey pubKeyReceiver = recvcert.getPublicKey(); // 2.4 Encrypting the SecretKey with the Receivers public Key byte[] byteEncryptWithPublicKey = encryptUtil.encryptData(senderSecretKey.getEncoded(),pubKeyReceiver,"RSA/ECB/PK CS1Padding"); String strSenbyteEncryptWithPublicKey = new BASE64Encoder().encode(byteEncryptWithPublicKey); // 3. Create a Message Digest of the Data to be transmitted md.update(byteDataToTransmit); byte byteMDofDataToTransmit[] = md.digest(); String strMDofDataToTransmit = new String(); for (int i = 0; i < byteMDofDataToTransmit.length; i++){ strMDofDataToTransmit = strMDofDataToTransmit + Integer.toHexString((int)byteMDofDataToTransmit[i] & 0xFF) ; } // 3.1 Message to be Signed = Encrypted Secret Key + MAC of the data to be transmitted String strMsgToSign = strSenbyteEncryptWithPublicKey + "|" + strMDofDataToTransmit; // 4. Sign the message // 4.1 Get the private key of the Sender from the keystore by providing the password set for the private key while creating the keys using keytool char[] keypassword = "send123".toCharArray(); Key myKey = ks.getKey("testsender", keypassword); PrivateKey myPrivateKey = (PrivateKey)myKey; // 4.2 Sign the message Signature mySign = Signature.getInstance("MD5withRSA"); mySign.initSign(myPrivateKey); mySign.update(strMsgToSign.getBytes()); byte[] byteSignedData = mySign.sign(); // 5. The Values byteSignedData (the signature) and strMsgToSign (the data which was signed) can be sent across to the receiver // 6.Validate the Signature // 6.1 Extracting the Senders public Key from his certificate X509Certificate sendercert ; CSE/8th /NS Lab/Prepared by Vivek Kumar Sinha
  • 12. Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur sendercert = (X509Certificate)ks.getCertificate("testsender"); PublicKey pubKeySender = sendercert.getPublicKey(); // 6.2 Verifying the Signature Signature myVerifySign = Signature.getInstance("MD5withRSA"); myVerifySign.initVerify(pubKeySender); myVerifySign.update(strMsgToSign.getBytes()); boolean verifySign = myVerifySign.verify(byteSignedData); if (verifySign == false) { System.out.println(" Error in validating Signature "); } else System.out.println(" Successfully validated Signature "); // 7. Decrypt the message using Recv private Key to get the Symmetric Key char[] recvpassword = "recv123".toCharArray(); Key recvKey = ks.getKey("testrecv", recvpassword); PrivateKey recvPrivateKey = (PrivateKey)recvKey; // Parsing the MessageDigest and the encrypted value String strRecvSignedData = new String (byteSignedData); String[] strRecvSignedDataArray = new String [10]; strRecvSignedDataArray = strMsgToSign.split("|"); int intindexofsep = strMsgToSign.indexOf("|"); String strEncryptWithPublicKey = strMsgToSign.substring(0,intindexofsep); String strHashOfData = strMsgToSign.substring(intindexofsep+1); // Decrypting to get the symmetric key byte[] bytestrEncryptWithPublicKey = new BASE64Decoder().decodeBuffer(strEncryptWithPublicKey); byte[] byteDecryptWithPrivateKey = encryptUtil.decryptData(byteEncryptWithPublicKey,recvPrivateKey,"RSA/ECB/PKCS1 Padding"); // 8. Decrypt the data using the Symmetric Key javax.crypto.spec.SecretKeySpec secretKeySpecDecrypted = new javax.crypto.spec.SecretKeySpec(byteDecryptWithPrivateKey,"AES"); byte[] byteDecryptText = encryptUtil.decryptData(byteCipherText,secretKeySpecDecrypted,"AES"); String strDecryptedText = new String(byteDecryptText); System.out.println(" Decrypted data is " +strDecryptedText); // 9. Compute MessageDigest of data + Signed message MessageDigest recvmd = MessageDigest.getInstance("MD5"); CSE/8th /NS Lab/Prepared by Vivek Kumar Sinha
  • 13. Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur recvmd.update(byteDecryptText); byte byteHashOfRecvSignedData[] = recvmd.digest(); String strHashOfRecvSignedData = new String(); for (int i = 0; i < byteHashOfRecvSignedData.length; i++){ strHashOfRecvSignedData = strHashOfRecvSignedData + Integer.toHexString((int)byteHashOfRecvSignedData[i] & 0xFF) ; } // 10. Validate if the Message Digest of the Decrypted Text matches the Message Digest of the Original Message if (!strHashOfRecvSignedData.equals(strHashOfData)) { System.out.println(" Message has been tampered "); } } catch(Exception exp) { System.out.println(" Exception caught " + exp); exp.printStackTrace() CSE/8th /NS Lab/Prepared by Vivek Kumar Sinha
  • 14. Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur EXPERIMENT NO. 07 Aim : Java network Security programming. Program:- SymmetricEncrypt import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.Cipher; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.InvalidKeyException; import java.security.InvalidAlgorithmParameterException; import javax.crypto.NoSuchPaddingException; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import sun.misc.BASE64Encoder; public class SymmetricEncrypt { String strDataToEncrypt = new String(); String strCipherText = new String(); String strDecryptedText = new String(); static KeyGenerator keyGen; private static String strHexVal = "0123456789abcdef"; public static SecretKey getSecret(){ try{ keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); } catch(Exception exp) { System.out.println(" Exception inside constructor " +exp); } CSE/8th /NS Lab/Prepared by Vivek Kumar Sinha
  • 15. Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur SecretKey secretKey = keyGen.generateKey(); return secretKey; } /** * Step2. Create a Cipher by specifying the following parameters * a. Algorithm name - here it is AES */ public byte[] encryptData(byte[] byteDataToEncrypt, Key secretKey, String Algorithm) { byte[] byteCipherText = new byte[200]; try { Cipher aesCipher = Cipher.getInstance(Algorithm); /** * Step 3. Initialize the Cipher for Encryption */ if(Algorithm.equals("AES")){ aesCipher.init(Cipher.ENCRYPT_MODE,secretKey,aesCipher.getParameters()); } else if(Algorithm.equals("RSA/ECB/PKCS1Padding")){ aesCipher.init(Cipher.ENCRYPT_MODE,secretKey); } byteCipherText = aesCipher.doFinal(byteDataToEncrypt); strCipherText = new BASE64Encoder().encode(byteCipherText); } catch (NoSuchAlgorithmException noSuchAlgo) { System.out.println(" No Such Algorithm exists " + noSuchAlgo); } catch (NoSuchPaddingException noSuchPad) { CSE/8th /NS Lab/Prepared by Vivek Kumar Sinha
  • 16. Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur System.out.println(" No Such Padding exists " + noSuchPad); } catch (InvalidKeyException invalidKey) { System.out.println(" Invalid Key " + invalidKey); } catch (BadPaddingException badPadding) { System.out.println(" Bad Padding " + badPadding); } catch (IllegalBlockSizeException illegalBlockSize) { System.out.println(" Illegal Block Size " + illegalBlockSize); illegalBlockSize.printStackTrace(); } catch (Exception exp) { exp.printStackTrace(); } return byteCipherText; } public byte[] decryptData(byte[] byteCipherText, Key secretKey, String Algorithm) { byte[] byteDecryptedText = new byte[200]; try{ Cipher aesCipher = Cipher.getInstance(Algorithm); if(Algorithm.equals("AES")){ aesCipher.init(Cipher.DECRYPT_MODE,secretKey,aesCipher.getParameters()); } else if(Algorithm.equals("RSA/ECB/PKCS1Padding")){ CSE/8th /NS Lab/Prepared by Vivek Kumar Sinha
  • 17. Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur aesCipher.init(Cipher.DECRYPT_MODE,secretKey); } byteDecryptedText = aesCipher.doFinal(byteCipherText); strDecryptedText = new String(byteDecryptedText); } catch (NoSuchAlgorithmException noSuchAlgo) { System.out.println(" No Such Algorithm exists " + noSuchAlgo); } catch (NoSuchPaddingException noSuchPad) { System.out.println(" No Such Padding exists " + noSuchPad); } catch (InvalidKeyException invalidKey) { System.out.println(" Invalid Key " + invalidKey); invalidKey.printStackTrace(); } catch (BadPaddingException badPadding) { System.out.println(" Bad Padding " + badPadding); badPadding.printStackTrace(); } catch (IllegalBlockSizeException illegalBlockSize) { System.out.println(" Illegal Block Size " + illegalBlockSize); illegalBlockSize.printStackTrace(); } catch (InvalidAlgorithmParameterException invalidParam) { System.out.println(" Invalid Parameter " + invalidParam); } CSE/8th /NS Lab/Prepared by Vivek Kumar Sinha
  • 18. Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur return byteDecryptedText; } public static byte[] convertStringToByteArray(String strInput) { strInput = strInput.toLowerCase(); byte[] byteConverted = new byte[(strInput.length() + 1) / 2]; int j = 0; int interimVal; int nibble = -1; for (int i = 0; i < strInput.length(); ++i) { interimVal = strHexVal.indexOf(strInput.charAt(i)); if (interimVal >= 0) { if (nibble < 0) { nibble = interimVal; } else { byteConverted[j++] = (byte) ((nibble << 4) + interimVal); nibble = -1; } } } if (nibble >= 0) { byteConverted[j++] = (byte) (nibble << 4); } if (j < byteConverted.length) { byte[] byteTemp = new byte[j]; System.arraycopy(byteConverted, 0, byteTemp, 0, j); byteConverted = byteTemp; } return byteConverted; } public static String convertByteArrayToString(byte[] block) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < block.length; ++i) { buf.append(strHexVal.charAt((block[i] >>> 4) & 0xf)); buf.append(strHexVal.charAt(block[i] & 0xf)); } return buf.toString(); } CSE/8th /NS Lab/Prepared by Vivek Kumar Sinha
  • 19. Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur EXPERIMENT NO. 08 Aim: Client Server Security Connection programming. Program:- class Main { public static void main(String[] args) { new TCPServer().start(); new TCPClient().start(); } } class TCPClient extends Thread { // Connection properties private static final String HOST = "127.0.0.1"; private static final int PORT = 56565; public void run() { // Socket class used for TCP connections Socket sock = null; // I/O components BufferedReader input = null; BufferedWriter output = null; try { // Connect our socket to the server. sock = new Socket(HOST, PORT); // Use a BufferedReader to read data from the server. input = new BufferedReader(new InputStreamReader(sock.getInputStream())); // Use a BufferedWriter to send data to the server. output = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())); // Send some data to the server. String toServer = "Are you there, Server?"; System.out.println("ToServer: " + toServer); output.write(toServer); output.newLine(); output.flush(); // Wait for a response from the server and display it. CSE/8th /NS Lab/Prepared by Vivek Kumar Sinha
  • 20. Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur String fromServer = input.readLine(); System.out.println("FromServer: " + fromServer); } catch (final IOException ex) { } finally { // Do our best to ensure a clean close procedure. // Closing the socket will also close input and output. try { if (sock != null) { sock.close(); } } catch (final IOException ex) { } } } } class TCPServer extends Thread { // Connection properties private static final int PORT = 56565; public void run() { // ServerSocket class used to accept TCP connections ServerSocket server = null; Socket sock = null; // I/O components BufferedReader input = null; BufferedWriter output = null; try { // Create our server on the given port. server = new ServerSocket(PORT); // Wait for a client to connect to us. sock = server.accept(); // Use a BufferedReader to read data from the client. input = new BufferedReader(new InputStreamReader(sock.getInputStream())); // Use a BufferedWriter to send data to the client. output = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())); // Wait for the client to talk to us. String fromClient = input.readLine(); CSE/8th /NS Lab/Prepared by Vivek Kumar Sinha
  • 21. Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur System.out.println("FromClient: " + fromClient); // Send them a response. String toClient = "Yes, I'm here, Client."; System.out.println("ToClient: " + toClient); output.write(toClient); output.newLine(); output.flush(); } catch (final IOException ex) { } finally { // Do our best to ensure a clean close procedure. // Closing the socket will also close input and output. try { if (sock != null) { sock.close(); } } catch (final IOException ex) { } // Close the server socket, as well. try { if (server != null) { server.close(); } } catch (final IOException ex) { } } } } CSE/8th /NS Lab/Prepared by Vivek Kumar Sinha
  • 22. Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur CSE/8th /NS Lab/Prepared by Vivek Kumar Sinha