Network Security Lab Manual - Google Docs
Network Security Lab Manual - Google Docs
No:1a
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.KeyGenerator;
import javax.crypto.SecretKey;
import java.util.Base64;
// Encryption
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
String plaintext = "Secure AES Communication";
byte[] encrypted = cipher.doFinal(plaintext.getBytes());
System.out.println("Ciphertext: " +
Base64.getEncoder().encodeToString(encrypted));
// Decryption
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decrypted = cipher.doFinal(encrypted);
System.out.println("Decrypted Text: " + new
String(decrypted));
}
}
1
OUTPUT:
Ciphertext: XO8HtvDQLk85N/w9lNttRWD0jkAQzu7hJzWaelxfmLw=
RESULT:
Implementation of symmetric key using AES was successfully executed and output is verified.
2
EX.No:1b
IMPLEMENT SYMMETRIC KEY ALGORITHM USING DES
Date:
AIM:
To implement the symmetric key algorithm using Data Encryption Standard (DES).
ALGORITHM:
1. Create an instance of the DES 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.KeyGenerator;
import javax.crypto.SecretKey;
import java.util.Base64;
3
System.out.println("Decrypted Text: " + decryptedText);
} catch (Exception e) {
e.printStackTrace();
}
}
}
4
OUTPUT:
RESULT:
Implementation of symmetric key using DES was successfully executed and output is verified.
5
EX.NO. : 2(A)
IMPLEMENT ASYMMETRIC KEY ALGORITHM USING RSA
DATE :
AIM:
To implement the asymmetric key algorithm using RSA.
ALGORITHM:
1. Key Generation: Use Java’s KeyPairGenerator to generate the RSA public
and private key pairs.
2. Encryption: Use Java's Cipher class to encrypt the plaintext using the public key.
3. Decryption: Use Java's Cipher class to decrypt the ciphertext using the private key.
PROGRAM :
import java.security.*;
import javax.crypto.*;
public class RSAExample {
// Method to generate RSA key pair
public static KeyPair generateRSAKeyPair(int keySize) throws NoSuchAlgorithmException
{ KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(keySize);
return keyPairGenerator.generateKeyPair();
}
// Method to encrypt the message using RSA public key
public static byte[] encryptMessage(PublicKey publicKey, String message) throws Exception { Cipher
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey); return cipher.doFinal(message.getBytes());
}
// Method to decrypt the message using RSA private key
public static String decryptMessage(PrivateKey privateKey, byte[] encryptedMessage) throws
Exception {
Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedBytes = cipher.doFinal(encryptedMessage); return new String(decryptedBytes);
}
public static void main(String[] args) { try {
// Generate RSA key pair (2048 bits)
KeyPair keyPair = generateRSAKeyPair(2048); String message = "Hello, RSA!";
System.out.println("Original Message: " + message);
// Encrypt the message using the public key
byte[] encryptedMessage = encryptMessage(keyPair.getPublic(), message);
System.out.println("Encrypted Message: " + new String(encryptedMessage));
// Decrypt the message using the private key
String decryptedMessage = decryptMessage(keyPair.getPrivate(), encryptedMessage);
System.out.println("Decrypted Message: " + decryptedMessage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
6
OUTPUT:
Original Message: Hello, RSA!
Encrypted Message: ?(x?£◄♥◄∟±→·?÷♂=å;-??Äè²??♣?+`?☻??ö!☺???¼r?♂?i\‼???ƒƒB?=♥?n!t??
qH.3◄?|?Éiª3?←?*W??4¡(??å?o⌂?p6CàG±?N⌂?▼!ñ½?/qò?7S???X«¼?&.?←0)¼?☺??;?Gß?
n»V<°♀U←??îD?Q6▬w?ó+?ö‼ïÇ!?·ÉÇ☼ìo4²2ïÆ‼>ô|?
Decrypted Message: Hello, RSA!
RESULT:
Implementation of Asymmetric key algorithm using RSA was successfully executed and output is
verified.
7
EX.No:2 (b)
IMPLEMENT ASYMMETRIC KEY EXCHANGE ALGORITHM
Date:
AIM:
ALGORITHM:
1. Key Generation: Use Java’s KeyPairGenerator class with the DH algorithm to
generate Diffie-Hellman key pairs.
2. Shared Secret Computation: Use Java's KeyAgreement class to compute the shared
secret using the private key and the other party's public key.
PROGRAM :
import java.security.*;
import javax.crypto.KeyAgreement;
import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.spec.DHParameterSpec;
import java.util.Base64;
// Generate key pair for Party 2 (Bob) using Alice's public key parameters
DHParameterSpec dhParameterSpec = ((DHPublicKey) publicKeyA).getParams();
keyPairGenerator.initialize(dhParameterSpec);
KeyPair keyPairB = keyPairGenerator.generateKeyPair();
PublicKey publicKeyB = keyPairB.getPublic();
PrivateKey privateKeyB = keyPairB.getPrivate();
} catch (Exception e) {
e.printStackTrace();
}
}
}
OUTPUT:
RESULT:
Implementation of Asymmetric Diffie-Hellman key exchange was successfully executed and output is
verified.
9
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 sender s 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.*;
import java.util.Base64;
10
// Verify the signature
signature.initVerify(publicKey);
signature.update(message.getBytes());
boolean isVerified = signature.verify(digitalSignature);
OUTPUT:
Original Message: This is a secure message.
Digital Signature: A1B2C3D4... (Base64 encoded signature)
Signature Verified: true
11
RESULT:
Thus the Digital Signature Standard Signature Scheme has been implemented and executed
successfully.
12
EX.No: 4
INSTALLATION OF WIRESHARK , TCPDUMP USING UDP/TCP
Date:
AIM:
Installation of Wireshark, TCPDUMP using UDP/TCP.
13
14
RESULT:
Thus, the Wireshark tool is installed successfully.
15
EX.No:5
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 keystore 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. Set up 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.BufferedReader;
import
java.io.InputStreamReader;
import java.io.OutputStream;
import javax.net.ssl.SSLServerSocket;
import
javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
public class SecureServer {
public static void main(String[] args)
{ try {
System.setProperty("javax.net.ssl.keyStore", "serverkeystore.jks");
System.setProperty("javax.net.ssl.keyStorePassword", "keystorepassword");
System.setProperty("javax.net.ssl.trustStore", "servertruststore.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "truststorepassword");
SSLServerSocketFactory sslServerSocketFactory = (SSLServerSocketFactory)
SSLServerSocketFactory.getDefault();
SSLServerSocket serverSocket = (SSLServerSocket)
sslServerSocketFactory.createServerSocket(9999);
System.out.println("Server waiting for client connection...");
SSLSocket sslSocket = (SSLSocket) serverSocket.accept();
System.out.println("Client connected.");
BufferedReader reader = new BufferedReader(new
InputStreamReader(sslSocket.getInputStream()));
16
OutputStream outputStream = sslSocket.getOutputStream();
String clientMessage = reader.readLine();
System.out.println("Received from client: " + clientMessage);
String processedMessage = "Processed: " + clientMessage;
outputStream.write(processedMessage.getBytes());
17
System.out.println("Sent to client: " + processedMessage);
reader.close();
outputStream.close();
sslSocket.close();
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}}
}
CLIENT ALGORITHM :
1. Set the path to the client's keystore and truststore files.
2. Create an SSL socket factory using the default SSL socket factory.
3. Create an SSL socket and connect to the server.
4. Set up 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 (perform any necessary operations).
9. Close the input/output streams and the SSL socket.
PROGRAM :
CLIENT
import java.io.BufferedReader;
import
java.io.InputStreamReader;
import java.io.OutputStream;
import javax.net.ssl.SSLSocket;
import
javax.net.ssl.SSLSocketFactory; public
class SecureClient {
public static void main(String[] args)
{ try {
System.setProperty("javax.net.ssl.keyStore", "clientkeystore.jks");
System.setProperty("javax.net.ssl.keyStorePassword", "keystorepassword");
System.setProperty("javax.net.ssl.trustStore", "clienttruststore.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "truststorepassword");
SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket("localhost", 9999);
System.out.println("Connected to server.");
BufferedReader reader = new BufferedReader(new
InputStreamReader(sslSocket.getInputStream()));
OutputStream outputStream = sslSocket.getOutputStream();
String message = "Hello from the client!";
System.out.println("Sending message to server: " + message);
outputStream.write(message.getBytes());
String serverResponse = reader.readLine(); System.out.println("Received
18
response from server: " + serverResponse); reader.close();
outputStream.close();
19
sslSocket.close();
} catch (Exception e) {
e.printStackTrace();
}}
}
SERVER OUTPUT:
Server waiting for client connection...
Client connected.
Received from client: Hello from the client!
Sent to client: Processed: Hello from the client!
CLIENT OUTPUT:
Connected to server.
Sending message to server: Hello from the client!
Received response from server: Processed: Hello from the client!
RESULT:
Thus the program to check message integrity and confidentiality using SSL was successfully
executed and output is verified.
20
EX. NO. : 6 EXPERIMENT ON EAVESDROPPING, DICTIONARY ATTACKS,
DATE : MITM ATTACKS
AIM:
To study on Eavesdropping, 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 Eavesdropping 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.
DICTIONARY ATTACKS:
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.
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.
22
MITM ATTACKS:
What is a Man-in-the-Middle (MITM) Attack?
Man-in-the-middle attacks (MITM) are a common type of cybersecurity 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.
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
introduce corrupt 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
Attackers 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 into
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 he has a session token.
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
23
HTTP equivalent endpoint, forcing the host to make requests to the server unencrypted.
Sensitive information can be leaked in plain text.
24
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 you
aren'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
proper page 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.
Attack Prevention
Strong WEP/WAP Encryption on Access Points.
Strong Router Login Credentials.
Virtual Private
Network.
Force HTTPS.
Public Key Pair Based Authentication.
RESULT:
Thus the Eavesdropping, dictionary attacks and MITM attacks are observed.
25
EX. NO: 7
EXPERIMENT WITH SNIFF TRAFFIC USING ARP POISONING
DATE :
AIM:
To study on sniff traffic using ARP poisoning.
Sniffing Attack:
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.
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.
Sniffing traffic using ARP poisoning is a type of cyberattack those abuses weaknesses in the
Address Resolution Protocol (ARP) to intercept, modify, or block network traffic between two
devices. ARP is a protocol that maps an IP address to a MAC address within a local network.
However, 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
To perform this attack, the attacker needs to have access to the same network as the target
devices, 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 they want 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
26
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.
27
EX. NO. : 8 DEMONSTRATE INTRUSION DETECTION SYSTEM USING
DATE : ANY TOOL
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 = "Some network traffic with a suspicious pattern";
String intrusionPattern = "suspicious pattern";
Pattern pattern = Pattern.compile(intrusionPattern);
Matcher matcher = pattern.matcher(networkTraffic);
if (matcher.find()) {
System.out.println("Intrusion detected: " + intrusionPattern);
} else {
System.out.println("No intrusion detected.");
}}}
OUTPUT:
Intrusion detected: suspicious pattern
RESULT:
Program to demonstrate intrusion detection system was successfully executed.
28
EX. NO. : 9
EXPLORE NETWORK MONITORING TOOL
DATE :
AIM:
ALGORITHM:
1. Start
2. Get Network Devices
3. Select a Network Interface
4. Open the Selected Interface
5. Start Packet Capture
6. Stop
PROGRAM:
import
jpcap.*; import
jpcap.packet.*;
public class NetworkMonitor {
public static void main(String[] args) throws Exception
{ NetworkInterface[] devices =
JpcapCaptor.getDeviceList(); if (devices.length == 0) {
System.out.println("No network interface found. Make sure you have the required
permissions.");
return;
}
int selectedDeviceIndex = 0;
NetworkInterface selectedDevice = devices[selectedDeviceIndex];
JpcapCaptor captor = JpcapCaptor.openDevice(selectedDevice, 2000, true,
20); System.out.println("Monitoring " + selectedDevice.name + "...");
while (true) {
Packet packet = captor.getPacket();
if (packet != null) {
System.out.println(packet);
}}}}
OUTPUT:
Ethernet packet (source MAC: 00:11:22:33:44:55, destination MAC: AA:BB:CC:DD:EE:FF)
IPv4 packet (source IP: 192.168.1.2, destination IP: 8.8.8.8, protocol: TCP)
TCP packet (source port: 12345, destination port: 80, flags: SYN)
Payload data: Hello, this is a sample packet!
29
RESULT:
Program for network monitoring tool are explored successfully.
30
EX. NO. : 10
STUDY TO CONFIGURE FIREWALL VPN
DATE :
AIM:
To study configure firewall VPN.
33