Network Security

Download as pdf or txt
Download as pdf or txt
You are on page 1of 43

Ex.

No:1 (A)
Implement Symmetric Key Algorithm Using AES
Date:

AIM:
To implement the symmetric key algorithm using AES.

ALGORITHM:
1. Create an instance of the AES Example class.
2. Set the original Val string that you want to encrypt.
3. Call the encrypt method with the original value.
4. Call the decrypt method with the encrypted value.
5. Print the original value, encrypted value, and decrypted value to the console.

PROGRAM:
Import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Scanner;

public class AES UserInput{

public static String encrypt(String key,string plaintext) throws Exception


{
Secret Key Spec secret Key=new Secret Key Spec(key.get Bytes(StandardCharsets.UTF_8),"AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

cipher .init(Cipher.ENCRYPT_MODE, secretKey);


byte[]encryptedBytes=cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
publicstatic Stringdecrypt(Stringkey,Stringciphertext)throws Exception {
SecretKeySpecsecretKey=newSecretKeySpec(key.getBytes(StandardCharsets.UTF_8),"AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);

byte[]decryptedBytes=cipher.doFinal(Base64.getDecoder().decode(ciphertext));
return new String(decryptedBytes, StandardCharsets.UTF_8);
}

publicstaticvoidmain(String[]args){ try {
Scannerscanner=newScanner(System.in);

//Input keyfrom user


System.out.print("Enterthekey(16,24,or32bytes):"); String
key = scanner.nextLine();

// Input plaintext from user


System.out.print("Entertheplaintext:");
String plaintext = scanner.nextLine();

// Encryption
String ciphertext = encrypt(key, plaintext);
System.out.println("Ciphertext:"+ciphertext);

// Decryption
String decryptedText = decrypt(key, ciphertext);
System.out.println("DecryptedText:"+decryptedText);

scanner.close();
}

catch(Exceptione)
{

e.printStackTrace();
}
}
}

SAMPLEOUTPUT:
Enter the key(16,24,or32bytes):1234567890123456
Enter the plaintext: Hello, AES!
Ciphertext:F1L+RZpVTAv7vxhYxypGsw==
Decrypted Text: Hello, AES

SAMPLEOUTPUT:

Original:Hello,RC6!
Encrypted:2A42B88F5D7998C36FD09F7C6D54C5D1
Decrypted:Hello,RC6!

RESULT:

Implementation of symmetric key using AES was successfully executed and output is verified.
Ex.No:1 (B)
Implement symmetric key algorithm using RC6
Date:

AIM:
To implement the symmetric key algorithm using AES.

ALGORITHM:
1. Print a message asking the user to enter a32-bitinput.
2. Open the file named"input.txt" for reading.
3. If the file is not found, handle the File Not Found Exception.
4. While there is a next line in the file:
5. Read the next line from the file.
6. Check if the line starts with "plaintext:".
7. If true, print the line.
8. Close the file reader.
9. End the program.

PROGRAM:
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
public class RC6 {
private static final int WORD_SIZE = 32;
private static final int NUM_ROUNDS=20;
private static final intKEY_SIZE=16;//16bytes=128bits
private int[] S;
public RC6(byte[]key)
{ keyExpansion(key);
}
privatevoidkeyExpansion(byte[]key){
int[] L = new int[key.length / 4];
for(int i = 0; i< key.length; i +=4) {
L[i/4]=ByteBuffer.wrap(key,i, 4).getInt();
}
intc=key.length/4;

int[]S=newint[2*NUM_ROUNDS+4]; S[0] =
0xB7E15163;
for(inti=1;i<S.length;i++){ S[i]
=S[i-1]+0x9E3779B9;
}
intA,B,i, j;
A =B =i = j =0;
intv=3*Math.max(c,S.length); for
(int s = 0; s < v; s++) {
A=S[i] =Integer.rotateLeft((S[i] +A+B) <<3,3);
B= L[j] = Integer.rotateLeft((L[j]+A+B)<<(A+B),A+B);
i= (i +1)% S.length;
j= (j +1)%c;
}
this.S =S;
}
public byte[] encrypt(byte[] plaintext)

Int blockSize=16;//16bytesperblock
int numBlocks = plaintext.length / blockSize;
byte[]ciphertext=newbyte[plaintext.length]; for
(int i = 0; i < numBlocks; i++) {
int[] block = new int[blockSize / 4];
for(intj =0; j<block.length;j++) {
block[j]=ByteBuffer.wrap(plaintext,i*blockSize+j*4, 4).getInt();
}
intA=block[0]+S[0];
intB=block[1]+S[1];
intC=block[2]+S[2];
intD =block[3]+S[3];
for(intround=1;round<=NUM_ROUNDS;round++){ A =
Integer.rotateLeft(A ^ B, B) + S[2 * round];
C=Integer.rotateLeft(C^D,D)+S[2*round+1];
B=Integer.rotateLeft(B^A,A)+S[2*round+2];
D=Integer.rotateLeft(D ^C,C) +S[2* round+3];

}
ByteBuffer.wrap(ciphertext, i * blockSize, 4).putInt(A);
ByteBuffer.wrap(ciphertext, i * blockSize + 4, 4).putInt(B);
ByteBuffer.wrap(ciphertext, i * blockSize + 8, 4).putInt(C);
ByteBuffer.wrap(ciphertext,i*blockSize+12,4).putInt(D);
}
return ciphertext;
}
public byte[] decrypt(byte[] ciphertext) {
intblockSize=16; //16 bytesper block
intnumBlocks=ciphertext.length/blockSize;
byte[]plaintext=newbyte[ciphertext.length];
for (int i = 0; i < numBlocks; i++) {
int[] block = new int[blockSize / 4];
for(intj =0; j<block.length;j++) {
block[j] =ByteBuffer.wrap(ciphertext,i*blockSize+j*4, 4).getInt();
}
intA=block[0];
intB=block[1];
intC=block[2];
int D = block[3];
for(intround=NUM_ROUNDS;round>=1;round--){ D =
Integer.rotateRight(D - S[2 * round + 3], C) ^ C;
B= Integer.rotateRight(B -S[2* round+2], A)^ A;
C=Integer.rotateRight(C-S[2*round+1],D)^D; A =
Integer.rotateRight(A - S[2 * round], B) ^ B;
}
A-=S[0];
B-=S[1];
C-=S[2];
D-=S[3];

ByteBuffer.wrap(plaintext, i * blockSize, 4).putInt(A);


ByteBuffer.wrap(plaintext,i*blockSize+4,4).putInt(B);
ByteBuffer.wrap(plaintext,i*blockSize+8,4).putInt(C);

ByteBuffer.wrap(plaintext,i*blockSize+12,4).putInt(D);

}
return plaintext;
}
publicstaticvoidmain(String[]args){
// Exampleusage
byte[]key="0123456789ABCDEF".getBytes(StandardCharsets.UTF_8);//16-bytekey byte[]
plaintext = "Hello, RC6!".getBytes(StandardCharsets.UTF_8);
RC6rc6=new RC6(key);
byte[]ciphertext=rc6.encrypt(plaintext.clone());//Clonetoavoidmodifyingtheoriginalarray byte[]
decryptedText = rc6.decrypt(ciphertext);
System.out.println("Original:"+newString(plaintext,StandardCharsets.UTF_8));
System.out.print("Encrypted: ");
printByteArrayAsHex(ciphertext);
System.out.println("\nDecrypted:"+newString(decryptedText,StandardCharsets.UTF_8));
}
privatestaticvoidprintByteArrayAsHex(byte[]array){ for
(byte b : array) {
System.out.print(String.format("%02X",b));
}
System.out.println();
}
}
SAMPLEOUTPUT:
Enter the key(upto56bytes):mySecretKey
Enter the plaintext: Hello, Blowfish!
Cipher text(Base64):DrnuwAAwC8C0Ec0zxLb9Yw==
Decrypted Text: Hello, Blowfish!

RESULT:
Implementation of symmetric key using RC6 was successfully executed and output is verified.
Ex.No:1 (C)
Implement Symmetric Key Algorithm Using BLOWFISH
Date:

AIM:
To implement the symmetric key algorithm using blowfish.

ALGORITHM:
1. Hard code a password and a key for demonstration purposes.
2. Print the original password.
3. Create an instance of Blow fish Demo.
4. Generate an encrypted text by calling the encrypt method with the password and key.
5. Print the encrypted text.
6. Decrypt the encrypted text using the decrypt method with the key.
7. Print the decrypted text.

PROGRAM:
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
importjava.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Scanner;

publicclassBlowfishImplementationWithInput{

publicstaticbyte[]encrypt(Stringkey, Stringplaintext) throwsException {


SecretKey secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8),
"Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE,secretKey);
returncipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
}

publicstaticStringdecrypt(Stringkey,byte[] ciphertext)throwsException
{

SecretKeysecretKey=newSecretKeySpec(key.getBytes(StandardCharsets.UTF_8),"Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[]decryptedBytes=cipher.doFinal(ciphertext);
returnnewString(decryptedBytes,StandardCharsets.UTF_8);
}

publicstaticvoidmain(String[]args){ try
{
Scannerscanner=newScanner(System.in);

//Input keyfrom user


System.out.print("Enterthekey(upto56bytes):"); String
key = scanner.nextLine();

// Input plaintext from user


System.out.print("Entertheplaintext:");
String plaintext = scanner.nextLine();

// Encryption
byte[] ciphertext = encrypt(key, plaintext);
System.out.println("Ciphertext(Base64):"+
Base64.getEncoder().encodeToString(ciphertext));

// Decryption
String decryptedText = decrypt(key, ciphertext);
System.out.println("DecryptedText:"+decryptedText);
scanner.close();
}catch(Exceptione){
e.printStackTrace();
}
}
}

SAMPLEOUTPUT:
Message data=12.000000

Encrypted data=3.000000
Original Message Sent= 12.000000

RESULT:

Implementation of symmetric key using blowfish was successfully executed and output is verified.
Ex.No:2 (A)
Implement Asymmetric Key Algorithm
Date:

AIM:
To implement the asymmetric key algorithm.

ALGORITHM:
1. Choose two prime numbers p and q.
2. Calculate n =p * q, which is part of the public key.
3. Choose a public exponent e such that it is co prime with (p-1)* (q-1)(denoted as phi).
4. Find a private exponent d such that (d* e)%phi=1.
N and e form the public key, while n and d form the private key.
5. Choose a message msg to be encrypted.
6. Encrypt the message using the public exponent e and modulus n.
7. Decrypt the cipher text using the private exponent d and modulus n.
8. Print the original message, encrypted data, and the decrypted original message.
9. Function to calculate the greatest common divisor(GCD)of two numbers.

PROGRAM:
import java.io.*;
importjava.math.*;
import java.util.*;
public class GFG
{
publicstatic doublegcd(doublea, double h)
{
doubletemp;
while (true)
{
temp = a % h;
if (temp == 0)
return h;
a=h;
h =temp;
}
}
publicstaticvoidmain(String[]args)
{
double p = 3;
double q = 7;
doublen=p*q;
double e = 2;
doublephi=(p-1)*(q-1); while (e
< phi) {
if(gcd(e,phi)==1) break;
elsee++;
}
int k =2;
doubled=(1+(k*phi))/e; double
msg = 12;
System.out.println("Messagedata="+msg);doublec=Math.pow(msg,e); c = c
% n;
System.out.println("Encrypteddata="+c);doublem=Math.pow(c,d); m = m
% n;
System.out.println("OriginalMessageSent= "+ m);
}
}
SAMPLEOUTPUT:
ThevalueofP:23 The
value of G : 9
TheprivatekeyaforAlice:4 The
private key b for Bob : 3
Secret key for the Alice is : 9
Secret Key for the Bob is : 9

RESULT:
Implementation of Asymmetric key was successfully executed and output is verified.
Ex.No:2 (B)
Implement Asymmetric Key Exchange Algorithm
Date:

AIM:
To implement the asymmetric key exchange algorithm.

ALGORITHM:
1. Initialize prime number P and primitive root G.
2. Choose private keys for Alice(a) and Bob(b).
3. Calculate public keys for Alice(x) and Bob(y) using the chosen primitive root and private
keys.
4. Calculate the shared secrets for Alice(ka) and Bob (kb)using their private keys and the other
party's public key.
5. Print the computed shared secrets for Alice and Bob.
6. Implement a power function to efficiently calculate modular exponentiation.

PROGRAM:
Class GFG{
private static long power(long a, long b, long p)
{
if(b==1)
return a;
else
return(((long)Math.pow(a,b))%p);
}
publicstaticvoidmain(String[]args)
{
longP,G,x,a,y,b,ka,kb; P =
23;
System.out.println("ThevalueofP:"+P); G
= 9;
System.out.println("ThevalueofG:"+G); a
= 4;
System.out.println("TheprivatekeyaforAlice:"+a); x =
power(G, a, P);
b =3;
System.out.println("TheprivatekeybforBob:"+b); y =
power(G, b, P);
ka=power(y,a,P);//SecretkeyforAlice kb =
power(x, b, P); // Secret key for Bob
System.out.println("SecretkeyfortheAliceis:"+ka);
System.out.println("Secret key for the Bob is:"+ kb);
}
}

SAMPLEOUTPUT:

RESULT:
Implementation of Asymmetric key exchange was successfully executed and outputis verified.
Ex.No:3
Implement Digital Signature Scheme
Date:

AIM:
To implement the signature scheme-Digital Signature Standard.

ALGORITHM:
1. Declare the class and required variables.
2. Create the object for the class in the main program.
3. Access the member functions using the objects.
4. Implement the SIGNATURE SCHEME-Digital Signature Standard.
5. It uses a hash function.
6. The hash code is provided as input to a signature function along with a random number K generated for
the particular signature.
7. The signature function also depends on the senders private key.
8. The signature consists of two components.
9. The hash code of the incoming message is generated.
10. The hash code and signature are given as input to a verification function.

PROGRAM:
Import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.util.Scanner;

public class Digital Signature Standard{


public static byte[]generate Signature(byte[]message Bytes,Private Key Key)throws
Exception {
Signature signature=Signature.getInstance("SHA256withRSA");
signature.init Sign(Key);
signature.update(messageBytes);
return signature.sign();
}

Public static Key Pair generate RSA Key Pair()throws Exception{ Secure
Random secure Random = new Secure Random();

Key Pair Generator key Pair Generator=Key Pair Generator.getInstance("RSA");


key Pair Generator.initialize (2048, secure Random);

Return key Pair Generator.generate Key Pair();


}
Public static Boolean is Verified Signature(byte[]message Bytes, byte[]signature Generated,
Public Key public Key) {
try{
Signature signature=Signature.getInstance("SHA256withRSA");
signature.initVerify(publicKey);
signature.update(messageBytes);

return signature.verify(signatureGenerated);

}catch (Exception e)

{ e.print StackTrace();
}
Return false;
}
public static void main(String[] args) {
Scannersc=new Scanner(System.in);
System.out.println("\nDigital Standard Signature\n");
System.out.println("Enter the message");
String message=sc.next();
try{

Key Pair key Pair=generate RSA Key Pair();


byte[]signature=generate Signature(message.getBytes(),keyPair.getPrivate());
//bytes to hex
System.out.println();
System.out.println("Signature Generated:");
for (byte b : signature) {

String hex=String.format("%02x",b);
System.out.print(hex);
}
System.out.println("\n");
if(isVerifiedSignature(message.getBytes(),signature,keyPair.getPublic())){
System.out.println("Signature is verified");
}else{
System.out.println("Signature is not verified");

}
}catch(Exceptione)

{ e.print Stack Trace();


}
}
}

SAMPLEOUTPUT:
RESULT:
Thus the Digital Signature Standard Signature Scheme has been implemented and the output
has been verified successfully.
Installation of Wireshark,tcpdump and observe data transferred
Ex.No:4
In client-server communication using UDP/TCP and identify the
Date:
UDP/TCP datagram.

AIM:
Installation of Wireshark,TCPDUMP using UDP/TCP.

ALGORITHM/STEPSTOINSTALLWIRESHARK:
Step1:Visit the official Wireshark website using any web browser.
Step2:Click on Download, a new webpage will open with different installers of Wireshark.
Step3:Downloading of the executable file will start shortly. It is a small73.69MBfile that will
take some time.
Step4: Now check for the executable file in downloads in your system and run it.
Step5: It will prompt confirmation to make changes to your system. Click on Yes. Step 6:
Setup screen will appear, click on Next.
Step7:The next screen will be of License Agreement, click on Noted.
Step 8: This screen is for choosing components, all components are already marked so don’t
change anything just click on the Next button.
Step 9: This screen is of choosing shortcuts like start menu or desktop icon along with file
extensions which can be intercepted by Wireshark, tick all boxes and click on Next button.
Step 10: The next screen will be of installing location so choose the drive which will have
sufficient memory space for installation. It needed only a memory space of 223.4 MB.
Step 11: Next screen has an option to install Npcap which is used with Wireshark to capture
packets pcap means packet capture so the install option is already checked don’t change anything and
click the next button.
Step 12: Next screen is about USB network capturing so it is one’s choice to use it or not, click
on Install.
Step13:After this installation process will start.
Step 14: This installation will prompt for Np cap installation as already checked so the license
agreement of Npcap will appear to click on the I Agree button.
Step15:Next screen is about different installing options of npcap,don’t do anything click on
Install.
Step16:After this installation process will start which will take only a minute.
Step17:After this installation
.
PROCESS:

Introduction The first part of the lab introduces packet sniffer,Wireshark.Wireshark is a free
open- source network protocol analyzer. It is used for network troubleshooting and
communication protocol analysis. Wireshark captures network packets in real time and display
them in human-readable format. It provides many advanced features including live capture and
offline analysis, three-pane packet browser, coloring rules for analysis. This document uses
Wireshark for the experiments, and it covers Wireshark installation, packet capturing, and
protocol analysis.
In the CSC 4190 Introduction to Computer Networking (one of the perquisite courses),
TCP/IP network stack is introduced and studied. This background section briefly explains the
concept of TCP/IP network stack to help you better understand the experiments. TCP/IP is the
most commonly used network model for Internet services. Because its most important protocols,
the Transmission Control Protocol (TCP) and the Internet Protocol (IP) were the first
networking protocols defined in this standard, it is named as TCP/IP. However, it contains
multiple layers including application layer, transport layer, network layer, and data link layer.
Application Layer: The application layer includes the protocols used by most
applications for providing user services. Examples of application layer protocols are Hypertext
Transfer Protocol (HTTP), Secure Shell (SSH), File Transfer Protocol (FTP), and Simple Mail
Transfer Protocol (SMTP).
Transport Layer:Thetransportlayer establishesprocess-to-process connectivity,
anditprovides end-to-end services that are independent of underlying user data. To implement
the process-to-process communication, the protocol introduces a concept of port. The examples
of transport layer protocols are Transport Control Protocol (TCP) and User Datagram Protocol
(UDP). The TCP provides flow- control, connection establishment, and reliable transmission of
data, while the UDP is a connectionless transmission model.
Internet Layer: The Internet layer is responsible for sending packets to across networks.
It has two functions: 1) Host identification by using IP addressing system (IPv4 and IPv6); and
2) packets routing from source to destination. The examples of Internet layer protocols are
Internet Protocol (IP), Internet Control Message Protocol (ICMP), and Address Resolution
Protocol (ARP).
Link Layer: The link layer defines the networking methods within the scope of the
local network link. It is used to move the packets between two hosts on the same link.An
common exampleof link layer protocols is Ethernet.
RESULT:

Thus, the Wireshark tool is installed successfully


Ex.No:5
Check message integrity and confidentiality using SSL
Date:

AIM:
To check message integrity and confidentiality using SSL.

SERVER ALGORITHM:
1. Set the path to the server's key store and trust store files.
2. Create an SSL server socket using the default SSL server socket factory.
3. Wait for a client connection by accepting incoming connections on the SSL
server socket.
4. Once a client connects ,create an SSL socket for communication.
5. Setup input and output streams for reading from and writing to the SSL socket.
6. Read the incoming message from the client.
7. Process the received message(perform any necessary operations).
8. Prepare a response message.
9. Write the response message to the output stream to send it back to the client.
10. Close the input/output streams and the SSL socket.
11. Close the SSL server socket.

PROGRAM:

SERVER
Import
java.io.Buffered
Reader; import
java.io.Input Stream
Reader; import
java.io.Output Stream;
import javax.net.ssl.SSL Server Socket;
import javax.net.ssl.SSLServer
Socket Factory; import
javax.net.ssl.SSL Socket;
public class Secure Server{
public static void
main(String[]args){ try {
System.set Property("javax.net.ssl.key Store", "server key
store.jks"); System.set Property("javax.net.ssl.key Store
Password","key store password");
SERVER SAMPLE OUTPUT :

Server waiting for

client connection...

Client connected.

Received from client: Hello from

the client! Sent to

client:Processed:Hello from the

client!

CLIENT SAMPLE OUTPUT:

Connected to server.

Sending message to server:Hello from the client!

Received response from server:Processed:Hello from the client!


System.setProperty("javax.net.ssl.trustStore",
"servertruststore.jks");
System.setProperty("javax.net.ssl.trustStorePassword",
"truststorepassword");
SSLServerSocketFactorysslServerSocketFactory=(SSLServerSo
cketFactory) SSLServerSocketFactory.getDefault();
SSLServerSocket serverSocket =
(SSLServerSocket)
sslServerSocketFactory.createServerSocket(99
99);
System.out.println("Serverwaitingforclientcon
nection..."); SSLSocket sslSocket =
(SSLSocket) serverSocket.accept();
System.out.println("Client connected.");
BufferedReader reader = new
BufferedReader(new
InputStreamReader(sslSocket.getInputStream()));
OutputStream outputStream =
sslSocket.getOutputStream(); String
clientMessage = reader.readLine();
System.out.println("Received from
client:"+client Message); String processed
Message = "Processed: " + client Message;
output Stream.write(processed
Message.getBytes()); System.out.println("Sent to
client: " + processed Message); reader.close();
Output Stream.close();
ssl Socket.close();
serverSocket.close();
}catch(E
xception
e){
e.printSt
ackTrace
();
}
}

}
CLIENT ALGORITHM:

1. Set the path to the client's key store and trust store files.
2. Create an SSL socket factory using the default SSL socket factory.
3. Create an SSL socket and connect to the server.
4. Setup input and output streams for reading from and writing to the SSL socket.
5. Prepare a message to send to the server.
6. Write the message to the output stream to end it to the server.
7. Read the response message from the server.
8. Process the received response(performance necessary operations).
9. Close the input/output streams and the SSL socket.

PROGRAM :

CLIENT

Import

java.io.BufferedRead

er; import

java.io.InputStreamRe

ader; import

java.io.OutputStream;

import

javax.net.ssl.SSLSock

et;

Import

javax.net.ssl.SSLSocketFa

ctory; public class Secure


Client {

Public static void

main(String[]args){ try {

System.setProperty("javax.net.ssl.keyStore", "client key store.jks");

System.setProperty("javax.net.ssl.key Store Password", "key store password");

System.setProperty("javax.net.ssl.trust Store", "client trust store.jks");

System.setProperty("javax.net.ssl.trust Store Password", "trust store password");

SSL SocketFactory sslSocketFactory = (SSL Socket Factory) SSL Socket

Factory.getDefault(); SSLSocket sslSocket = (SSLSocket) ssl Socket

Factory.create Socket("local host", 9999); System.out.println("Connected to

server.");

Buffered Reader reader=new


Buffered reader(new Input Stream
Reader(ssl Socket.getInputStream()));

Output Stream output Stream = ssl Socket.get

Outputstream(); String message = "Hello from

the client!"; System.out.println("Sending

message to

server:"+message);outputStream.write(message.g

etBytes());

StringserverResponse=reader.readLine();

System.out.println("Receivedresponsefromserver:"+serverRes
ponse); reader.close();

outputStream.close();

sslSocket.close();
}catch(E

xception

e){

e.printSt

ackTrace

();

Sample Output
Strong WEP/WAP Encryption on
Access Points. Strong Router Login
Credentials.
Virtual Private Network
.Force HTTPS. Public Key
Pair Based Authentication.

RESULT:

Thus the program to check message integrity and confidentiality using SSL was
successfully executed and output is verified.
Ex.No:6
Experiment On Eaves dropping, Dictionary Attacks, Mitm Attacks
Date:

AIM:
To study on Eaves dropping, Dictionary attacks and MITM attacks.

EAVESDROPPING:
Definition:
An Eavesdropping attack occurs when a hacker intercepts, deletes, or modifies data
that is transmitted between two devices. Eavesdropping, also known as sniffing or
snooping, relies on unsecured network communications to access data in transit
between devices. The data is transmitted across an open network, which gives an
attacker the opportunity to exploit vulnerability and intercept it via various methods.
Eavesdropping attacks can often be difficult to spot.
Attacks:
Eavesdropping attacks are a big threat to the integrity and confidentiality of
the data. It allows an attacker to gather sensitive information, such as login credentials,
financial data, or personal conversations, without the victim’s knowledge. Furthermore,
attackers can use the extracted information for various malicious purposes, such as
identity theft, extortion, or espionage.
Let’s look at the general steps in order to launch an Eaves dropping attack:
The first step is identifying a target for the attack, such as a specific individual or
organization. As soon as the attacker identifies the target, it starts gathering information
about it. Some useful information the attacker wants to extract includes the
communication systems and vulnerabilities that can be exploited.
The next step is to choose an appropriate method for the successful execution of the
attack. There’re several different methods that an attacker can use. Some examples are
intercepting communication over unsecured networks, using malware to gain access to
a device, or using hardware devices.
The next step is to execute the chosen method in the target system and intercept the
target’s communication. Finally, the attacker analyzes the intercepted communication
and extracts valuable information.
Prevention Techniques:
We can use several techniques to prevent eavesdropping attacks. Some popular
techniques include encryption, virtual private networks, secure communication
protocols, firewalls, and network segmentation. Encrypting communication makes it
difficult for attackers to intercept and read messages. In order to encrypt
communication, we can use different types of encryption algorithms, such as
symmetric key algorithms and public key algorithms. Advanced Encryption Standard
(AES) is an example of a symmetric key algorithm. Additionally, Rivest–Shamir–
Adleman (RSA) is a widely used public key algorithm.
Virtual private networks (VPNs) create a secure, encrypted connection between a
device and a remote server. They can help to prevent eaves dropping attacks by
encrypting communication and making it difficult for attackers to intercept.
DICTIONARYATTACKS:
Definition:
A dictionary attack is a method of breaking into a password-protected computer,
network or other IT resource by systematically entering every word in a dictionary as a
password. A dictionary attack can also be used in an attempt to find the key necessary
to decrypt an encrypted message or document.
Dictionary attacks work because many computer users and businesses insist on
using ordinary words as passwords. These attacks are usually unsuccessful against
systems using multiple-word passwords and are also often unsuccessful against
passwords made up of uppercase and lowercase letters and numbers in random
combinations.

How do dictionary attacks work?


A dictionary attack uses a preselected library of words and phrases to guess
possible passwords. It operates under the assumption that users tend to pull from a
basic list of passwords, such as "password,""123abc" and "123456."
These lists include predictable patterns that can vary by region. For example,
hackers looking to launch a dictionary attack on a New York-based group of targets
might look to test phrases like "knicksfan2020" or "newyorkknicks1234." Attackers
incorporate words related to sports teams, monuments, cities, addresses and other
regionally specific items when building their attack library dictionaries.
How effective is a dictionary attack?
How successful a dictionary attack is depending on how strong the
passwords are for the individuals a hacker is targeting. Because weak passwords are
still common, attackers continue to have success with these attacks. Individual users,
however, aren't the only ones who are subject to weak password security.
Take steps to prevent a dictionary attack
Dictionary hacking is a very common type of cybercrime that hackers use to
gain access to an individual’s personal accounts, including bank accounts, social media
profiles, and emails. With this access, hackers can perpetrate all sorts of actions, from
financial fraud and malicious social media posts to further cybercrimes like phishing.
However, dictionary attack prevention can be as simple as implementing certain
safeguards to minimize the risk of falling victim to these attacks. Using smart password
management habits, employing different types of authentications, and using readily
available password managers, for example, can all help keep passwords and accounts
secure.

MITM ATTACKS:
What is a Man-in-the-Middle(MITM)Attack?
Man-in-the-middle attacks (MITM) are a common type of cyber security
attack that allows attackers to eavesdrop on the communication between two targets.
The attack takes place in between two legitimately communicating hosts, allowing the
attacker to “listen” to a conversation they should normally not be able to listen to,
hence the name “man-in-the-middle.
Types of Man-
in-the-Middle
Attacks Rogue
Access Point
Devices equipped with wireless cards will often try to auto-connect to the
access point that is
emittingthestrongestsignal.Attackerscansetuptheirownwirelessaccess point and trick
near by devices to join its domain.
ARP Spoofing
ARP is the Address Resolution Protocol. It is used to resolve IP addresses to
physical MAC (media access control) addresses in a local area network. When a host
needs to talk to a host with a given IP address, it references the ARP cache to resolve
the IP address to a MAC address.
MDNS Spoofing
Multicast DNS is similar to DNS, but it’s done on a local area network
(LAN) using broadcast like ARP. This makes it a perfect target for spoofing attacks.
The local name resolution system is supposed to make the configuration of network
devices extremely simple.
DNS Spoofing
Similar to the way ARP resolves IP addresses to MAC addresses on a LAN,
DNS resolves domain names to IP addresses. When using a DNS spoofing attack, the
attacker attempts to introducecorrupt DNS cache information to a host in an attempt to
access another host using their domain name, such as www.onlinebanking.com.
Man-in-the-Middle Attack Techniques Sniffing
Attacker use packet capture tools to inspect packets at a low level. Using
specific wireless devices that are allowed to be put into monitoring or promiscuous
mode can allow an attacker to see packets
That are not intended for it to see,such as packets addressed to other hosts.
Packet Injection
An attacker can also leverage their device’s monitoring mode to inject
malicious packets in to data communication streams. The packets can blend in with
valid data communication streams, appearing to be part of the communication, but
malicious in nature. Packet injection usually involves first sniffing to determine how
and when to craft and send packets.
Session Hijacking
Most web applications use a login mechanism that generates a temporary
session token to use for future requests to avoid requiring the user to type a password at
every page. An attacker can sniff sensitive traffic to identify the session token for a
user and use it to make requests as the user.
The attacker does not need to spoof once
hehasa session to ken. SSL Stripping
Since using HTTPS is a common safeguard against ARP or DNS spoofing,
attackers use SSL stripping to intercept packets and alter their HTTPS-based address
requests to go to their HTTP equivalent endpoint, forcing the host to make requests to
the server unencrypted. Sensitive information can be leaked in plain text.
How to Detect a Man-in-the-Middle Attack
Detecting a Man-in-the-middle attack can be difficult without taking the
proper steps. If youaren't actively searching to determine if your communications have
been intercepted, a
Man-in-the-middle attack can potentially go unnoticed until it's too late.
Checking for properpage authentication and implementing some sort of tamper
detection are typically the key methods to detect a possible attack, but these procedures
might require extra forensic analysis after-the-fact.

RESULT:

Thus the Eaves dropping, dictionary attacks and MITM attacks are observed.
Ex.No:7
Experiment With Sniff Traffic Using Arp Poisoning
Date:

AIM:
To study on sniff traffic using ARP poisoning.
Sniffing Attack:
Sniffing Attack in context of network security, corresponds to theft or
interception of data by capturing the network traffic using a packet sniffer (an
application aimed at capturing network packets). When data is transmitted across
networks, if the data packets are not encrypted, the data within the network packet
can be read using a sniffer. Using a sniffer application, an attacker can analyse the
network and gain information to eventually cause the network to crashor to become
corrupted,or read the communications happening across the network.
Sniffing attacks can be compared to tapping of phone wires and get to know
about the conversation, and for this reason, it is also referred as wiretapping applied
to computer networks. Using sniffing tools, attackers can sniff sensitive information
from a network, including email (SMTP, POP, IMAP), web (HTTP), FTP (Telnet
authentication, FTP Passwords, SMB, NFS) and many more types of network traffic.
The packet sniffer usually sniffs the network data without making any modifications
in the network's packets. Packet sniffers can just watch, display, and log the traffic,
and this information can be accessed by the attacker.
What is ARP Poisoning?
ARP Poisoning consists of abusing the weaknesses in ARP to corrupt the
MAC-to-IP mappings of other devices on the network. Security was not a paramount
concern when ARP was introduced in 1982, so the designers of the protocol never
included authentication mechanisms to validate ARP messages. Any device on the
network can answer an ARP request, whether the original message was intended for
it or not. For example, if Computer A “asks” for the MAC address of Computer B,
an attacker at Computer C can respond and Computer A would accept this response
as authentic. This oversight has made a variety of attacks possible. By leveraging
easily available tools, a threat actor can “poison” the ARP cache of other hosts on a
local network, filling the ARP cache with inaccurate entries.
Sniff traffic using ARP poisoning:
Sniffing traffic using ARP poisoning is a type of cyber attack those abuses
weaknesses in the Address Resolution Protocol (ARP) to intercept, modify, or block
network traffic between two devices. ARP is a protocol that map san IP address to a
MAC address within a local network. How ever,ARP lacks authentication
mechanisms, and this is what the attack exploits. The attacker sends fake ARP
responses to a specific host on the network, thus linking the attacker’s MAC address
to the IP address of another host, such as the network’s gateway. As a result, the
target host sends all its network traffic to the attacker instead of the intended host
Toperformthisattack,theattackerneedstohaveaccesstothesamenetworkasthetar
getdevices, and use a tool that can send out forged ARP responses, such as Arp
spoof or Driftnet. The attacker configures the tool with their MAC address and the
IP addresses of the two devices theywant to intercept

traffic between. The forged responses tell both devices that the correct MAC address
for each of them is the attacker’s MAC address. As a result, both devices start
sending all their network traffic to the attacker’s machine, thinking it’s the other
device they want to communicate with.
The attacker can then do various things with the incorrectly directed traffic.
If the attacker chooses to inspect the traffic, they can steal sensitive information,
such as passwords, account details, or credit card numbers. If they decide to modify
the traffic, they can inject malicious scripts, such as malware, ransomware, or
phishing links. Finally, if they choose to block the traffic, they can perform a Denial
of Service (DoS) attack, where they completely stop the communication between the
two devices.
ARP poisoning is a serious threat to network security, as it can compromise
the confidentiality, integrity, and availability of network data. To prevent ARP
poisoning attacks, some possible countermeasures are:
Using network monitoring tools, such as Wireshark or Nmap, to detect any
anomalies or suspicious activities on the network, such as duplicate MAC addresses,
ARP requests, or ARP responses.

RESULT:

Thus,the sniff traffic using ARP poisoning observed.


Ex.No:8
Demonstrate Intrusion Detection System Using Any Tool
Date:

AIM:

To demonstrate intrusion detection system using any tool.

ALGORITHM:
1. Start
2. Initialize Network Traffic and Intrusion Pattern
3. Compile Regular Expression.
4. Match Pattern in Network Traffic.
5. Print a message indicating the intrusion detection: "Intrusion detected:".
6. Print a message indicating no intrusion: "No intrusion detected.".
7. Stop

PROGRAM:
import java.util.regex.*;
public class SimpleIDS{
public static void main(String[]args){
String networkTraffic="Somenetworktrafficwithasuspiciouspattern";StringintrusionPattern= "suspicious
pattern";
Pattern pattern = Pattern.compile(intrusion Pattern); Matcher matcher = pattern.matcher(networkTraffic);
if (matcher.find()) {
System.out.println("Intrusion detected:"+ intrusion Pattern);
}else {
System.out.println("No intrusion detected.");
}
}
}
SAMPLEOUTPUT:

Intrusion detected: suspicious pattern

RESULT:

Program to demonstrate intrusion detection system was successfully executed.


Ex.No:9
Explore Network Monitoring Tool
Date:

AIM:
To explore network monitoring tool.

ALGORITHM:
1. Start
2. Get Network Devices
3. Select a Network Interface
4. Open the Selected Interface
5. StartPacketCapture
6. Stop

PROGRAM:
Import jpcap.*;

import jpcap.packet.*;
public class Network Monitor{
public static void main(String[] args) throws Exception { Network Interface[] devices =
JpcapCaptor.getDeviceList(); if (devices.length == 0) {
System.out.println("No network interface found.Make sure you have the required permissions.");
return;
}
intselectedDeviceIndex=0;
NetworkInterface selectedDevice = devices[selectedDeviceIndex]; JpcapCaptor captor =
JpcapCaptor.openDevice(selectedDevice, 2000, true, 20); System.out.println("Monitoring " +
selectedDevice.name + "...");
while(true){
Packetpacket=captor.getPacket();if (packet!=null){System.out.println(packet);
}
}
}
SAMPLEOUTPUT:
Ethernetpacket(source MAC:00:11:22:33:44:55,destinationMAC:AA:BB:CC:DD:EE:FF) IPv4packet
(source IP: 192.168.1.2, destination IP: 8.8.8.8, protocol: TCP)
TCPpacket (source port: 12345, destination port: 80, flags:SYN) Payload data: Hello, this isa
samplepacket!

RESULT:

Program for network monitoring tool are explored successfully.


Ex.No:10
Study To Configure Firewall VPN
Date:

AIM:
To study configure firewall VPN.
Create and Configure the Network
Initialize the network:
1. OpentheObjectPalettedialogboxbyclicking.Makesurethattheinternettoolbox item is
selected from the pull-down menu on the object palette.
2. Add the following objects from the palette to the project workspace (see the following figure for
placement): Application Config, Profile Config, an ip32_cloud, one ppp_ server, three
ethernet4_slip8_gtwy routers, and two pppwkstn hosts.
3. RenametheobjectsyouaddedandconnectthemusingPPP_DS1links,asshown.
The Firewall Scenario
In the network we just created, the Sales Person profile allows both sales sites to access applications such
as database access, email, and Web browsing from the server (check the Profile Configuration of the
Profiles node). Assume that we need to protect the database in the server from external access, including
the salespeople. One way to do that is to replace
Router C with a firewall as follows:
1. Select Duplicate Scenario from the Scenarios menu and name it Firewall. Click OK.
2. In the new scenario, right-click on Router C·Edit Attributes.
3. Assign ethernet2_slip8_firewall to the model attribute.
4. Expand the hierarchy of the Proxy Server Information attribute · Expand the row 1, which is for
the database application hierarchy · Assign No to the Proxy Server Deployed
Attribute as shown. Click OK,and Save your project.
TheFirewallVPNScenario
In the Firewall scenario, we protected the databases in the server from “any” external access using
a firewall router. Assume that we want to allow the people in the Sales A site to have access to the
databases in the server. Because the firewall filters all database-related traffic regard less of the source of
the traffic, we need to consider the VPN solution. A virtual tunnel can be used by Sales A to senddatabase
requests to the server. The firewall will not filter the traffic created by Sales A because the IP packets in
the tunnel will be encapsulated inside an IP datagram.

1. While you are in theFirewall scenario,select Duplicate Scenario from the Scenarios menu and give
it the name Firewall_VPN · Click OK.
2. Remove the link between RouterC and the Server.
3. Open the Object Palette dialogbox by clicking.Make sure that the internet tool box is selected
from the pull-down menu on the object palette.
a. Add to the project workspace one ethernet4_slip8_gtwyandoneIPVPNConfig(seethe following
figure for placement).
b. From the Object palette,use two PPP_DS1links to connect the new router to the RouterC(the
firewall) and to the Server, as shown in the following figure.
c. Close the Object Palette dialog box.
4. Rename the IP VPN Config object to VPN.
5. Rename the new router to Router Das shown in the following fig.
RESULT:

Thus,the configure to firewall VPN observed.

You might also like