Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
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];
}
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");
CSE/SRIT/8th
/NS Lab/Prepared by Vivek Kumar Sinha
Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur
break;
}
i++;
}
CSE/SRIT/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);
}
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
CSE/SRIT/8th
/NS Lab/Prepared by Vivek Kumar Sinha
Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur
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/SRIT/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/SRIT/8th
/NS Lab/Prepared by Vivek Kumar Sinha
Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur
CSE/SRIT/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);
} }
import java.net.*;
CSE/SRIT/8th
/NS Lab/Prepared by Vivek Kumar Sinha
Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur
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/SRIT/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/SRIT/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/SRIT/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/SRIT/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/SRIT/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/SRIT/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/SRIT/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/SRIT/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/SRIT/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/SRIT/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/SRIT/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/SRIT/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/SRIT/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/SRIT/8th
/NS Lab/Prepared by Vivek Kumar Sinha

More Related Content

What's hot

Ch11 Basic Cryptography
Ch11 Basic CryptographyCh11 Basic Cryptography
Ch11 Basic Cryptography
Information Technology
 
File System Implementation - Part1
File System Implementation - Part1File System Implementation - Part1
File System Implementation - Part1
Amir Payberah
 
Cryptography and Information Security
Cryptography and Information SecurityCryptography and Information Security
Cryptography and Information Security
Dr Naim R Kidwai
 
CRYPTOGRAPHY & NETWORK SECURITY - unit 1
CRYPTOGRAPHY & NETWORK SECURITY -  unit 1CRYPTOGRAPHY & NETWORK SECURITY -  unit 1
CRYPTOGRAPHY & NETWORK SECURITY - unit 1
RAMESHBABU311293
 
Public Key Cryptosystem
Public Key CryptosystemPublic Key Cryptosystem
Public Key Cryptosystem
Devakumar Kp
 
Wireshark Basic Presentation
Wireshark Basic PresentationWireshark Basic Presentation
Wireshark Basic Presentation
MD. SHORIFUL ISLAM
 
Block Cipher and its Design Principles
Block Cipher and its Design PrinciplesBlock Cipher and its Design Principles
Block Cipher and its Design Principles
SHUBHA CHATURVEDI
 
Computer networks a tanenbaum - 5th editionee
Computer networks   a tanenbaum - 5th editioneeComputer networks   a tanenbaum - 5th editionee
Computer networks a tanenbaum - 5th editionee
pawan1809
 
5. protocol layering
5. protocol layering5. protocol layering
5. protocol layering
JAIGANESH SEKAR
 
Network lab manual
Network lab manualNetwork lab manual
Network lab manual
Prabhu D
 
Dag representation of basic blocks
Dag representation of basic blocksDag representation of basic blocks
Dag representation of basic blocks
Jothi Lakshmi
 
Inter Process Communication
Inter Process CommunicationInter Process Communication
Inter Process Communication
Anil Kumar Pugalia
 
Monoalphabetic Substitution Cipher
Monoalphabetic Substitution  CipherMonoalphabetic Substitution  Cipher
Monoalphabetic Substitution Cipher
SHUBHA CHATURVEDI
 
Rotor Cipher and Enigma Machine
Rotor Cipher and Enigma MachineRotor Cipher and Enigma Machine
Rotor Cipher and Enigma Machine
Saurabh Kaushik
 
MAC-Message Authentication Codes
MAC-Message Authentication CodesMAC-Message Authentication Codes
MAC-Message Authentication Codes
DarshanPatil82
 
Key management and distribution
Key management and distributionKey management and distribution
Key management and distribution
Riya Choudhary
 
CoAP - Web Protocol for IoT
CoAP - Web Protocol for IoTCoAP - Web Protocol for IoT
CoAP - Web Protocol for IoT
Aniruddha Chakrabarti
 
Octave
OctaveOctave
Octave
Amar Myana
 
Data Encryption Standard (DES)
Data Encryption Standard (DES)Data Encryption Standard (DES)
Data Encryption Standard (DES)
Haris Ahmed
 
Subnetting Presentation
Subnetting PresentationSubnetting Presentation
Subnetting Presentation
Touhidul Fahim
 

What's hot (20)

Ch11 Basic Cryptography
Ch11 Basic CryptographyCh11 Basic Cryptography
Ch11 Basic Cryptography
 
File System Implementation - Part1
File System Implementation - Part1File System Implementation - Part1
File System Implementation - Part1
 
Cryptography and Information Security
Cryptography and Information SecurityCryptography and Information Security
Cryptography and Information Security
 
CRYPTOGRAPHY & NETWORK SECURITY - unit 1
CRYPTOGRAPHY & NETWORK SECURITY -  unit 1CRYPTOGRAPHY & NETWORK SECURITY -  unit 1
CRYPTOGRAPHY & NETWORK SECURITY - unit 1
 
Public Key Cryptosystem
Public Key CryptosystemPublic Key Cryptosystem
Public Key Cryptosystem
 
Wireshark Basic Presentation
Wireshark Basic PresentationWireshark Basic Presentation
Wireshark Basic Presentation
 
Block Cipher and its Design Principles
Block Cipher and its Design PrinciplesBlock Cipher and its Design Principles
Block Cipher and its Design Principles
 
Computer networks a tanenbaum - 5th editionee
Computer networks   a tanenbaum - 5th editioneeComputer networks   a tanenbaum - 5th editionee
Computer networks a tanenbaum - 5th editionee
 
5. protocol layering
5. protocol layering5. protocol layering
5. protocol layering
 
Network lab manual
Network lab manualNetwork lab manual
Network lab manual
 
Dag representation of basic blocks
Dag representation of basic blocksDag representation of basic blocks
Dag representation of basic blocks
 
Inter Process Communication
Inter Process CommunicationInter Process Communication
Inter Process Communication
 
Monoalphabetic Substitution Cipher
Monoalphabetic Substitution  CipherMonoalphabetic Substitution  Cipher
Monoalphabetic Substitution Cipher
 
Rotor Cipher and Enigma Machine
Rotor Cipher and Enigma MachineRotor Cipher and Enigma Machine
Rotor Cipher and Enigma Machine
 
MAC-Message Authentication Codes
MAC-Message Authentication CodesMAC-Message Authentication Codes
MAC-Message Authentication Codes
 
Key management and distribution
Key management and distributionKey management and distribution
Key management and distribution
 
CoAP - Web Protocol for IoT
CoAP - Web Protocol for IoTCoAP - Web Protocol for IoT
CoAP - Web Protocol for IoT
 
Octave
OctaveOctave
Octave
 
Data Encryption Standard (DES)
Data Encryption Standard (DES)Data Encryption Standard (DES)
Data Encryption Standard (DES)
 
Subnetting Presentation
Subnetting PresentationSubnetting Presentation
Subnetting Presentation
 

Viewers also liked

Graphics User Interface Lab Manual
Graphics User Interface Lab ManualGraphics User Interface Lab Manual
Graphics User Interface Lab Manual
Vivek Kumar Sinha
 
microprocessor 8086 lab manual !!
microprocessor 8086 lab manual !!microprocessor 8086 lab manual !!
microprocessor 8086 lab manual !!
Sushil Mishra
 
Npc13
Npc13Npc13
Main ds manual
Main ds manualMain ds manual
Main ds manual
Vivek Kumar Sinha
 
Network security mannual (2)
Network security mannual (2)Network security mannual (2)
Network security mannual (2)
Vivek Kumar Sinha
 
Pslb lab manual
Pslb lab manualPslb lab manual
Pslb lab manual
Vivek Kumar Sinha
 
Cn lab manual
Cn lab manualCn lab manual
Cn lab manual
Vivek Kumar Sinha
 
Company Profile - Compressed
Company Profile - CompressedCompany Profile - Compressed
Company Profile - Compressed
Solly Moeng - APR
 
Computer applications in civil engineering lab
Computer applications in civil engineering labComputer applications in civil engineering lab
Computer applications in civil engineering lab
Vivek Kumar Sinha
 
Lab manual asp.net
Lab manual asp.netLab manual asp.net
Lab manual asp.net
Vivek Kumar Sinha
 
Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015
Buşra Deniz, CSM
 
Teks ekposisi
Teks ekposisiTeks ekposisi
Teks ekposisi
BERBUDIANTO
 
Mech nacp lab
Mech nacp labMech nacp lab
Mech nacp lab
Vivek Kumar Sinha
 
Java final lab
Java final labJava final lab
Java final lab
Vivek Kumar Sinha
 
Computer hardware and simulation lab manual
Computer  hardware and simulation lab manualComputer  hardware and simulation lab manual
Computer hardware and simulation lab manual
Vivek Kumar Sinha
 
Oops lab manual
Oops lab manualOops lab manual
Oops lab manual
Vivek Kumar Sinha
 
Softwareenggineering lab manual
Softwareenggineering lab manualSoftwareenggineering lab manual
Softwareenggineering lab manual
Vivek Kumar Sinha
 
Network Programming
Network ProgrammingNetwork Programming
Network Programming
Vinayak Hegde
 
Cse 7 softcomputing lab
Cse 7 softcomputing labCse 7 softcomputing lab
Cse 7 softcomputing lab
Vivek Kumar Sinha
 
Eurest Breakfast White Paper
Eurest Breakfast White PaperEurest Breakfast White Paper
Eurest Breakfast White Paper
Gaurang Patel
 

Viewers also liked (20)

Graphics User Interface Lab Manual
Graphics User Interface Lab ManualGraphics User Interface Lab Manual
Graphics User Interface Lab Manual
 
microprocessor 8086 lab manual !!
microprocessor 8086 lab manual !!microprocessor 8086 lab manual !!
microprocessor 8086 lab manual !!
 
Npc13
Npc13Npc13
Npc13
 
Main ds manual
Main ds manualMain ds manual
Main ds manual
 
Network security mannual (2)
Network security mannual (2)Network security mannual (2)
Network security mannual (2)
 
Pslb lab manual
Pslb lab manualPslb lab manual
Pslb lab manual
 
Cn lab manual
Cn lab manualCn lab manual
Cn lab manual
 
Company Profile - Compressed
Company Profile - CompressedCompany Profile - Compressed
Company Profile - Compressed
 
Computer applications in civil engineering lab
Computer applications in civil engineering labComputer applications in civil engineering lab
Computer applications in civil engineering lab
 
Lab manual asp.net
Lab manual asp.netLab manual asp.net
Lab manual asp.net
 
Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015
 
Teks ekposisi
Teks ekposisiTeks ekposisi
Teks ekposisi
 
Mech nacp lab
Mech nacp labMech nacp lab
Mech nacp lab
 
Java final lab
Java final labJava final lab
Java final lab
 
Computer hardware and simulation lab manual
Computer  hardware and simulation lab manualComputer  hardware and simulation lab manual
Computer hardware and simulation lab manual
 
Oops lab manual
Oops lab manualOops lab manual
Oops lab manual
 
Softwareenggineering lab manual
Softwareenggineering lab manualSoftwareenggineering lab manual
Softwareenggineering lab manual
 
Network Programming
Network ProgrammingNetwork Programming
Network Programming
 
Cse 7 softcomputing lab
Cse 7 softcomputing labCse 7 softcomputing lab
Cse 7 softcomputing lab
 
Eurest Breakfast White Paper
Eurest Breakfast White PaperEurest Breakfast White Paper
Eurest Breakfast White Paper
 

Similar to Network security Lab manual

Pemrograman Jaringan
Pemrograman JaringanPemrograman Jaringan
Pemrograman Jaringan
belajarkomputer
 
123
123123
TCP IP
TCP IPTCP IP
TCP IP
hivasu
 
Basic socket programming
Basic socket programmingBasic socket programming
Basic socket programming
Kristian Arjianto
 
iPhone and Rails integration
iPhone and Rails integrationiPhone and Rails integration
iPhone and Rails integration
Paul Ardeleanu
 
Report for weather pi
Report for weather piReport for weather pi
Report for weather pi
Asutosh Hota
 
Socket programming in c
Socket programming in cSocket programming in c
Socket programming in c
Md. Golam Hossain
 
Npc14
Npc14Npc14
Arduino práctico ethernet
Arduino práctico   ethernetArduino práctico   ethernet
Arduino práctico ethernet
Jose Antonio Vacas
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket Programming
Vipin Yadav
 
proxyc CSAPP Web proxy NAME IMPORTANT Giv.pdf
  proxyc  CSAPP Web proxy   NAME    IMPORTANT Giv.pdf  proxyc  CSAPP Web proxy   NAME    IMPORTANT Giv.pdf
proxyc CSAPP Web proxy NAME IMPORTANT Giv.pdf
ajay1317
 
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
MARRY7
 
Socket programming
Socket programming Socket programming
Socket programming
Rajivarnan (Rajiv)
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.com
phanleson
 
Winform
WinformWinform
Winform
quocphu199
 
ikh331-06-distributed-programming
ikh331-06-distributed-programmingikh331-06-distributed-programming
ikh331-06-distributed-programming
Anung Ariwibowo
 
A.java
A.javaA.java
sockets
socketssockets
Lab manual cn-2012-13
Lab manual cn-2012-13Lab manual cn-2012-13
Lab manual cn-2012-13
Sasi Kala
 
forwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docxforwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docx
budbarber38650
 

Similar to Network security Lab manual (20)

Pemrograman Jaringan
Pemrograman JaringanPemrograman Jaringan
Pemrograman Jaringan
 
123
123123
123
 
TCP IP
TCP IPTCP IP
TCP IP
 
Basic socket programming
Basic socket programmingBasic socket programming
Basic socket programming
 
iPhone and Rails integration
iPhone and Rails integrationiPhone and Rails integration
iPhone and Rails integration
 
Report for weather pi
Report for weather piReport for weather pi
Report for weather pi
 
Socket programming in c
Socket programming in cSocket programming in c
Socket programming in c
 
Npc14
Npc14Npc14
Npc14
 
Arduino práctico ethernet
Arduino práctico   ethernetArduino práctico   ethernet
Arduino práctico ethernet
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket Programming
 
proxyc CSAPP Web proxy NAME IMPORTANT Giv.pdf
  proxyc  CSAPP Web proxy   NAME    IMPORTANT Giv.pdf  proxyc  CSAPP Web proxy   NAME    IMPORTANT Giv.pdf
proxyc CSAPP Web proxy NAME IMPORTANT Giv.pdf
 
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
 
Socket programming
Socket programming Socket programming
Socket programming
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.com
 
Winform
WinformWinform
Winform
 
ikh331-06-distributed-programming
ikh331-06-distributed-programmingikh331-06-distributed-programming
ikh331-06-distributed-programming
 
A.java
A.javaA.java
A.java
 
sockets
socketssockets
sockets
 
Lab manual cn-2012-13
Lab manual cn-2012-13Lab manual cn-2012-13
Lab manual cn-2012-13
 
forwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docxforwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docx
 

More from Vivek Kumar Sinha

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

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

PCI Design Handbook Content and Updates.pptx
PCI Design Handbook Content and Updates.pptxPCI Design Handbook Content and Updates.pptx
PCI Design Handbook Content and Updates.pptx
gunjanatulbansal
 
RAILWAYS, a vital part of our infrastructure, play a crucial role in ensuring...
RAILWAYS, a vital part of our infrastructure, play a crucial role in ensuring...RAILWAYS, a vital part of our infrastructure, play a crucial role in ensuring...
RAILWAYS, a vital part of our infrastructure, play a crucial role in ensuring...
Kiran Kumar Manigam
 
buy a fake University of London diploma supplement
buy a fake University of London diploma supplementbuy a fake University of London diploma supplement
buy a fake University of London diploma supplement
GlethDanold
 
image processing image enhancement and filtering
image processing image enhancement and filteringimage processing image enhancement and filtering
image processing image enhancement and filtering
Sophia804451
 
UNIT-I-METAL CASTING PROCESSES -Manufact
UNIT-I-METAL CASTING PROCESSES -ManufactUNIT-I-METAL CASTING PROCESSES -Manufact
UNIT-I-METAL CASTING PROCESSES -Manufact
Mr.C.Dineshbabu
 
Numerical comaprison of various order explicit runge kutta methods with matla...
Numerical comaprison of various order explicit runge kutta methods with matla...Numerical comaprison of various order explicit runge kutta methods with matla...
Numerical comaprison of various order explicit runge kutta methods with matla...
DrAzizulHasan1
 
BLW vocational training mechanical production workshop report.
BLW vocational training mechanical production workshop report.BLW vocational training mechanical production workshop report.
BLW vocational training mechanical production workshop report.
nk3275141
 
Reciprocating Air Compressor and its Types
Reciprocating Air Compressor and its TypesReciprocating Air Compressor and its Types
Reciprocating Air Compressor and its Types
Atif Razi
 
Thermodynamics and Heat Transfer - KRCE.pptx
Thermodynamics and Heat Transfer - KRCE.pptxThermodynamics and Heat Transfer - KRCE.pptx
Thermodynamics and Heat Transfer - KRCE.pptx
krceseo
 
The X Window System Graphical User Interface
The X Window System Graphical User InterfaceThe X Window System Graphical User Interface
The X Window System Graphical User Interface
hindirahuerfano
 
抖音人气博主卖逼【网祉:5j8.net】反差幼师【网祉:5j8.net】中国农村野战
抖音人气博主卖逼【网祉:5j8.net】反差幼师【网祉:5j8.net】中国农村野战抖音人气博主卖逼【网祉:5j8.net】反差幼师【网祉:5j8.net】中国农村野战
抖音人气博主卖逼【网祉:5j8.net】反差幼师【网祉:5j8.net】中国农村野战
【网祉:5j8.net】 极品美鲍【网祉:5j8.net】
 
2300/2800 series Perkins diesel engine.pdf
2300/2800 series Perkins diesel engine.pdf2300/2800 series Perkins diesel engine.pdf
2300/2800 series Perkins diesel engine.pdf
haytham majed
 
Presentation on ergonomics in mining industry
Presentation on ergonomics in mining industryPresentation on ergonomics in mining industry
Presentation on ergonomics in mining industry
praku727
 
SM_5th-SEM_Cse_Mobile-Computing.pdf_________________
SM_5th-SEM_Cse_Mobile-Computing.pdf_________________SM_5th-SEM_Cse_Mobile-Computing.pdf_________________
SM_5th-SEM_Cse_Mobile-Computing.pdf_________________
smarakd64
 
Good Energy Haus: PHN Presents Building Electrification, A Passive House Symp...
Good Energy Haus: PHN Presents Building Electrification, A Passive House Symp...Good Energy Haus: PHN Presents Building Electrification, A Passive House Symp...
Good Energy Haus: PHN Presents Building Electrification, A Passive House Symp...
TE Studio
 
A Case of Unrecognized Peripartum Cardiomyopathy Which Was Noticed During Eme...
A Case of Unrecognized Peripartum Cardiomyopathy Which Was Noticed During Eme...A Case of Unrecognized Peripartum Cardiomyopathy Which Was Noticed During Eme...
A Case of Unrecognized Peripartum Cardiomyopathy Which Was Noticed During Eme...
CrimsonPublishers-SBB
 
Computer Vision and GenAI for Geoscientists.pptx
Computer Vision and GenAI for Geoscientists.pptxComputer Vision and GenAI for Geoscientists.pptx
Computer Vision and GenAI for Geoscientists.pptx
Yohanes Nuwara
 
Gen AI with LLM for construction technology
Gen AI with LLM for construction technologyGen AI with LLM for construction technology
Gen AI with LLM for construction technology
Tae wook kang
 
UNIT-1-INTRODUCTION- MECHATRONICS-ENGGINERING
UNIT-1-INTRODUCTION- MECHATRONICS-ENGGINERINGUNIT-1-INTRODUCTION- MECHATRONICS-ENGGINERING
UNIT-1-INTRODUCTION- MECHATRONICS-ENGGINERING
Chandra Kumar S
 
AI INTERACTION WITH HUMAN IN DAILY LIFE (1).pptx
AI INTERACTION WITH HUMAN IN DAILY LIFE (1).pptxAI INTERACTION WITH HUMAN IN DAILY LIFE (1).pptx
AI INTERACTION WITH HUMAN IN DAILY LIFE (1).pptx
MoinKhan447017
 

Recently uploaded (20)

PCI Design Handbook Content and Updates.pptx
PCI Design Handbook Content and Updates.pptxPCI Design Handbook Content and Updates.pptx
PCI Design Handbook Content and Updates.pptx
 
RAILWAYS, a vital part of our infrastructure, play a crucial role in ensuring...
RAILWAYS, a vital part of our infrastructure, play a crucial role in ensuring...RAILWAYS, a vital part of our infrastructure, play a crucial role in ensuring...
RAILWAYS, a vital part of our infrastructure, play a crucial role in ensuring...
 
buy a fake University of London diploma supplement
buy a fake University of London diploma supplementbuy a fake University of London diploma supplement
buy a fake University of London diploma supplement
 
image processing image enhancement and filtering
image processing image enhancement and filteringimage processing image enhancement and filtering
image processing image enhancement and filtering
 
UNIT-I-METAL CASTING PROCESSES -Manufact
UNIT-I-METAL CASTING PROCESSES -ManufactUNIT-I-METAL CASTING PROCESSES -Manufact
UNIT-I-METAL CASTING PROCESSES -Manufact
 
Numerical comaprison of various order explicit runge kutta methods with matla...
Numerical comaprison of various order explicit runge kutta methods with matla...Numerical comaprison of various order explicit runge kutta methods with matla...
Numerical comaprison of various order explicit runge kutta methods with matla...
 
BLW vocational training mechanical production workshop report.
BLW vocational training mechanical production workshop report.BLW vocational training mechanical production workshop report.
BLW vocational training mechanical production workshop report.
 
Reciprocating Air Compressor and its Types
Reciprocating Air Compressor and its TypesReciprocating Air Compressor and its Types
Reciprocating Air Compressor and its Types
 
Thermodynamics and Heat Transfer - KRCE.pptx
Thermodynamics and Heat Transfer - KRCE.pptxThermodynamics and Heat Transfer - KRCE.pptx
Thermodynamics and Heat Transfer - KRCE.pptx
 
The X Window System Graphical User Interface
The X Window System Graphical User InterfaceThe X Window System Graphical User Interface
The X Window System Graphical User Interface
 
抖音人气博主卖逼【网祉:5j8.net】反差幼师【网祉:5j8.net】中国农村野战
抖音人气博主卖逼【网祉:5j8.net】反差幼师【网祉:5j8.net】中国农村野战抖音人气博主卖逼【网祉:5j8.net】反差幼师【网祉:5j8.net】中国农村野战
抖音人气博主卖逼【网祉:5j8.net】反差幼师【网祉:5j8.net】中国农村野战
 
2300/2800 series Perkins diesel engine.pdf
2300/2800 series Perkins diesel engine.pdf2300/2800 series Perkins diesel engine.pdf
2300/2800 series Perkins diesel engine.pdf
 
Presentation on ergonomics in mining industry
Presentation on ergonomics in mining industryPresentation on ergonomics in mining industry
Presentation on ergonomics in mining industry
 
SM_5th-SEM_Cse_Mobile-Computing.pdf_________________
SM_5th-SEM_Cse_Mobile-Computing.pdf_________________SM_5th-SEM_Cse_Mobile-Computing.pdf_________________
SM_5th-SEM_Cse_Mobile-Computing.pdf_________________
 
Good Energy Haus: PHN Presents Building Electrification, A Passive House Symp...
Good Energy Haus: PHN Presents Building Electrification, A Passive House Symp...Good Energy Haus: PHN Presents Building Electrification, A Passive House Symp...
Good Energy Haus: PHN Presents Building Electrification, A Passive House Symp...
 
A Case of Unrecognized Peripartum Cardiomyopathy Which Was Noticed During Eme...
A Case of Unrecognized Peripartum Cardiomyopathy Which Was Noticed During Eme...A Case of Unrecognized Peripartum Cardiomyopathy Which Was Noticed During Eme...
A Case of Unrecognized Peripartum Cardiomyopathy Which Was Noticed During Eme...
 
Computer Vision and GenAI for Geoscientists.pptx
Computer Vision and GenAI for Geoscientists.pptxComputer Vision and GenAI for Geoscientists.pptx
Computer Vision and GenAI for Geoscientists.pptx
 
Gen AI with LLM for construction technology
Gen AI with LLM for construction technologyGen AI with LLM for construction technology
Gen AI with LLM for construction technology
 
UNIT-1-INTRODUCTION- MECHATRONICS-ENGGINERING
UNIT-1-INTRODUCTION- MECHATRONICS-ENGGINERINGUNIT-1-INTRODUCTION- MECHATRONICS-ENGGINERING
UNIT-1-INTRODUCTION- MECHATRONICS-ENGGINERING
 
AI INTERACTION WITH HUMAN IN DAILY LIFE (1).pptx
AI INTERACTION WITH HUMAN IN DAILY LIFE (1).pptxAI INTERACTION WITH HUMAN IN DAILY LIFE (1).pptx
AI INTERACTION WITH HUMAN IN DAILY LIFE (1).pptx
 

Network security Lab manual

  • 1. 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]; } 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"); CSE/SRIT/8th /NS Lab/Prepared by Vivek Kumar Sinha
  • 2. Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur break; } i++; } CSE/SRIT/8th /NS Lab/Prepared by Vivek Kumar Sinha
  • 3. 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); } memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; CSE/SRIT/8th /NS Lab/Prepared by Vivek Kumar Sinha
  • 4. Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur 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/SRIT/8th /NS Lab/Prepared by Vivek Kumar Sinha
  • 5. 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/SRIT/8th /NS Lab/Prepared by Vivek Kumar Sinha
  • 6. Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur CSE/SRIT/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); } } import java.net.*; CSE/SRIT/8th /NS Lab/Prepared by Vivek Kumar Sinha
  • 8. Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur 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/SRIT/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/SRIT/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/SRIT/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/SRIT/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/SRIT/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/SRIT/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/SRIT/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/SRIT/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/SRIT/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/SRIT/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/SRIT/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/SRIT/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/SRIT/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/SRIT/8th /NS Lab/Prepared by Vivek Kumar Sinha