CSS EXP1 Merged

You might also like

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

EXPERIMENT-1

Aim: To implement Caesar Cipher, Vignere Cipher and Rail-fence Cipher.

Theory:
A. Caesar cipher
● The Caesar cipher is a simple encryption technique that was used by Julius Caesar to
send secret messages to his allies. It works by shifting the letters in the plaintext message
by a certain number of positions, known as the “shift” or “key”.
● The Caesar Cipher technique is one of the earliest and simplest methods of encryption
technique. It’s simply a type of substitution cipher, i.e., each letter of a given text is
replaced by a letter with a fixed number of positions down the alphabet. For example
with a shift of 1, A would be replaced by B, B would become C, and so on. The method
is apparently named after Julius Caesar, who apparently used it to communicate with his
officials.
● Thus to cipher a given text we need an integer value, known as a shift which indicates the
number of positions each letter of the text has been moved down.
● The encryption can be represented using modular arithmetic by first transforming the
letters into numbers, according to the scheme, A = 0, B = 1,…, Z = 25. Encryption of a
letter by a shift n can be described mathematically as.
● For example, if the shift is 3, then the letter A would be replaced by the letter D, B would
become E, C would become F, and so on. The alphabet is wrapped around so that after Z,
it starts back at A.
● Here is an example of how to use the Caesar cipher to encrypt the message “HELLO”
with a shift of 3:
● Write down the plaintext message: HELLO
● Choose a shift value. In this case, we will use a shift of 3.
● Replace each letter in the plaintext message with the letter that is three positions to the
right in the alphabet.
H becomes K (shift 3 from H)
E becomes H (shift 3 from E)
L becomes O (shift 3 from L)
L becomes O (shift 3 from L)
O becomes R (shift 3 from O)

The encrypted message is now “KHOOR”.


Code:
import time
def encrypt(text, s):

result = ""
start_time = time.time()

# Traverse text
for i in range(len(text)):
char = text[i]

# Encrypt uppercase characters


if char.isupper():
result += chr((ord(char) + s - 65) % 26 + 65)

# Encrypt lowercase characters


elif char.islower():
result += chr((ord(char) + s - 97) % 26 + 97)

# Keep other characters unchanged


else:
result += char

end_time = time.time()
print("Time taken for encryption: {:.6f} seconds".format(end_time - start_time))

return result

def decrypt(text, s):

result = ""
start_time = time.time()

# Traverse text
for i in range(len(text)):
char = text[i]
# Decrypt uppercase characters
if char.isupper():
result += chr((ord(char) - s - 65) % 26 + 65)

# Decrypt lowercase characters


elif char.islower():
result += chr((ord(char) - s - 97) % 26 + 97)

# Keep other characters unchanged


else:
result += char

end_time = time.time()
print("Time taken for decryption: {:.6f} seconds".format(end_time - start_time))

return result

# Input text and shift value


text = input("Enter text to encrypt: ")
s = int(input("Enter the shift value: "))

print("Text : " + text)


print("Shift : " + str(s))

# Encrypt the text


encrypted_text = encrypt(text, s)
print("Cipher: " + encrypted_text)

# Decrypt the encrypted text using the same shift value


decrypted_text = decrypt(encrypted_text, s)
print("Decrypted Text: " + decrypted_text)
B. Vigenere Cipher
Vigenere Cipher is a method of encrypting alphabetic text. It uses a simple form of
polyalphabetic substitution. A polyalphabetic cipher is any cipher based on substitution, using
multiple substitution alphabets. The encryption of the original text is done using the Vigenère
square or Vigenère table.

● The table consists of the alphabets written out 26 times in different rows, each alphabet
shifted cyclically to the left compared to the previous alphabet, corresponding to the 26
possible Caesar Ciphers.
● At different points in the encryption process, the cipher uses a different alphabet from one
of the rows.
● The alphabet used at each point depends on a repeating keyword.

Encryption:
The first letter of the plaintext, G is paired with A, the first letter of the key. So use row G and
column A of the Vigenère square, namely G. Similarly, for the second letter of the plaintext, the
second letter of the key is used, the letter at row E, and column Y is C. The rest of the plaintext is
enciphered in a similar fashion.
Decryption:
Decryption is performed by going to the row in the table corresponding to the key, finding the
position of the ciphertext letter in this row, and then using the column’s label as the plaintext. For
example, in row A (from AYUSH), the ciphertext G appears in column G, which is the first
plaintext letter. Next, we go to row Y (from AYUSH), locate the ciphertext C which is found in
column E, thus E is the second plaintext letter.A more easy implementation could be to visualize
Vigenère algebraically by converting [A-Z] into numbers [0–25].
● Encryption
The plaintext(P) and key(K) are added modulo 26.
Ei = (Pi + Ki) mod 26
● Decryption
Di = (Ei - Ki) mod 26

Code:
import time
# This function generates the
# key in a cyclic manner until
# it's length isn't equal to
# the length of original text
def generateKey(string, key):
key = list(key)
if len(string) == len(key):
return(key)
else:
for i in range(len(string) - len(key)):
key.append(key[i % len(key)])
return("".join(key))

# This function returns the


# encrypted text generated
# with the help of the key
def cipherText(string, key):
cipher_text = []
for i in range(len(string)):
x = (ord(string[i]) + ord(key[i])) % 26
x += ord('A')
cipher_text.append(chr(x))
return("".join(cipher_text))

# This function decrypts the


# encrypted text and returns
# the original text
def originalText(cipher_text, key):
orig_text = []
for i in range(len(cipher_text)):
x = (ord(cipher_text[i]) - ord(key[i]) + 26) % 26
x += ord('A')
orig_text.append(chr(x))
return("".join(orig_text))

# Driver code
if __name__ == "__main__":
string = input("Enter the text needed for encryption: ").upper()
keyword = input("Enter the keyword: ").upper()

start_encryption_time = time.time()
key = generateKey(string, keyword)
cipher_text = cipherText(string,key)
end_encryption_time = time.time()
start_decryption_time = time.time()
original_text = originalText(cipher_text, key)
end_decryption_time = time.time()

print("Ciphertext:", cipher_text)
print("Original/Decrypted Text:", original_text)
print("Time taken for encryption:", end_encryption_time - start_encryption_time, "seconds")
print("Time taken for decryption:", end_decryption_time - start_decryption_time, "seconds")

C. Rail-fence
Given a plain-text message and a numeric key, cipher/decipher the given text using the Rail
Fence algorithm.
The rail fence cipher (also called a zigzag cipher) is a form of transposition cipher. It derives its
name from the way in which it is encoded.
● Encryption
In a transposition cipher, the order of the alphabets is rearranged to obtain the cipher-text. In the
rail fence cipher, the plain-text is written downwards and diagonally on successive rails of an
imaginary fence.
When we reach the bottom rail, we traverse upwards moving diagonally, after reaching the top
rail, the direction is changed again. Thus the alphabets of the message are written in a zig-zag
manner.After each alphabet has been written, the individual rows are combined to obtain the
cipher-text.
● Decryption
As we’ve seen earlier, the number of columns in rail fence cipher remains equal to the length of a
plain-text message. And the key corresponds to the number of rails.Hence, the rail matrix can be
constructed accordingly. Once we’ve got the matrix we can figure-out the spots where texts
should be placed (using the same way of moving diagonally up and down alternatively ).Then,
we fill the cipher-text row wise. After filling it, we traverse the matrix in a zig-zag manner to
obtain the original text.
Code:
#include <iostream>
#include <vector>
#include <string>

using namespace std;

// Function to encrypt a message


string encryptRailFence(string text, int key) {
int len = text.length();
vector<vector<char>> rail(key, vector<char>(len, '\n'));

bool dir_down = false;


int row = 0, col = 0;

for (int i = 0; i < len; i++) {


if (row == 0 || row == key - 1) {
dir_down = !dir_down;
}

rail[row][col++] = text[i];

if (dir_down) {
row++;
} else {
row--;
}
}

string result;
for (int i = 0; i < key; i++) {
for (int j = 0; j < len; j++) {
if (rail[i][j] != '\n') {
result.push_back(rail[i][j]);
}
}
}

return result;
}

// Function to decrypt a message


string decryptRailFence(string cipher, int key) {
int len = cipher.length();
vector<vector<char>> rail(key, vector<char>(len, '\n'));

bool dir_down;
int row = 0, col = 0;

for (int i = 0; i < len; i++) {


if (row == 0) {
dir_down = true;
}
if (row == key - 1) {
dir_down = false;
}

rail[row][col++] = '*';

if (dir_down) {
row++;
} else {
row--;
}
}
int index = 0;
for (int i = 0; i < key; i++) {
for (int j = 0; j < len; j++) {
if (rail[i][j] == '*' && index < len) {
rail[i][j] = cipher[index++];
}
}
}

string result;
row = 0, col = 0;
for (int i = 0; i < len; i++) {
if (row == 0) {
dir_down = true;
}
if (row == key - 1) {
dir_down = false;
}

if (rail[row][col] != '*') {
result.push_back(rail[row][col++]);
}

if (dir_down) {
row++;
} else {
row--;
}
}

return result;
}

// Driver code
int main() {
string text;
int key;

cout << "Enter the original text: ";


getline(cin, text);
cout << "Enter the level: ";
cin >> key;

string enc = encryptRailFence(text, key);


string dec = decryptRailFence(enc, key);

cout << "Encrypted: " << enc << endl;


cout << "Decrypted: " << dec << endl;

return 0;
}

Conclusion: Hence we have successfully implemented one of each monoalphabetic,


polyalphabetic and transposition ciphers.
EXPERIMENT- 2

AIM: To Implement a digital Signature Scheme using RSA Algorithm

THEORY: -
RSA algorithm is an asymmetric cryptography algorithm. Asymmetric actually means that
it works on two different keys i.e. Public Key and Private Key. As the name describes that
the Public Key is given to everyone and the Private key is kept private.
Digital Signature: As the name sounds are the new alternative to sign a document digitally.
It ensures that the message is sent by the intended user without any tampering by any third
party (attacker). In simple words, digital signatures are used to verify the authenticity of the
message sent electronically.

RSA is a widely used algorithm for digital signatures because it provides strong security
and efficient performance. Digital signatures are used to verify the authenticity of digital
documents and ensure that they have not been tampered with. The process of creating a
digital signature involves the following steps:

● Hashing: The first step in creating a digital signature is to create a hash of the
message or document that needs to be signed. This is done using a hash function,
which produces a fixed-length output (the hash value) from an input of any size.
● Signing: The hash value is then encrypted using the private key of the signer. This
produces the digital signature, which is attached to the original message or
document.
● Verification: To verify the authenticity of the digital signature, the recipient of the
message or document must first decrypt the signature using the public key of the
signer. This produces the original hash value. The recipient then calculates the hash
value of the received message or document using the same hash function that was
used by the signer. If the two hash values match, the signature is valid and the
message or document has not been tampered with.

RSA is well-suited for digital signatures because it provides strong security and efficient
performance. The security of RSA is based on the difficulty of factoring large prime
numbers. In RSA, the private key is a pair of prime numbers, and the public key is a product
of these primes. Because factoring the public key into its prime factors is considered a
computationally difficult problem, it is infeasible for an attacker to deduce the private key
from the public key.
Furthermore, RSA is efficient because the signing process only involves modular
exponentiation, which is a relatively fast operation. This makes it suitable for use in a
wide range of applications, including digital certificates, secure email, and electronic
commerce.
1. Key Generation:

- Generate two large prime numbers, p and q.

- Calculate n = p * q.

- Compute φ(n) = (p - 1) * (q - 1).

- Choose an integer e such that 1 < e < φ(n) and gcd(e, φ(n)) = 1.

- Calculate d such that (d * e) mod φ(n) = 1.

2. Signature Generation:

- Hash the message to a fixed length.

- Treat the hash value as a large integer, m.

- Compute the signature, s, as s = m^d mod n.


3. Signature Verification:

- Obtain the original hash value, m, from the signature, s, using s^e mod n.

- Hash the message to be verified.

- Compare the obtained hash value with the hash value of the message.

Time Complexity: O(log(min(m, n))


CODE:

import math

def gcd(a, h):

temp = 0

while(1):

temp = a % h

if (temp == 0):

return h

a=h

h = temp

p=3

q=7

n = p*q

e=2

phi = (p-1)*(q-1)
while (e < phi):

# e must be co-prime to phi and

# smaller than phi.

if(gcd(e, phi) == 1):

break

else:

e = e+1

# Private key (d stands for decrypt)

# choosing d such that it satisfies

# d*e = 1 + k * totient

k=2

d = (1 + (k*phi))/e

# Message to be
encrypted msg = 12.0

print("Message data = ", msg)

# Encryption c = (msg ^
e) % n c = pow(msg, e)

c = math.fmod(c, n)
print("Encrypted data = ", c)

# Decryption m = (c ^
d) % n m = pow(c, d)

m = math.fmod(m, n)

print("Original Message Sent = ", m)


OUTPUT: -
Conclusion:The RSA algorithm provides a robust method for digital signature schemes. It
ensures authenticity, integrity, and non-repudiation of digital messages. By generating public
and private keys, signing the message with the private key, and verifying the signature with
the public key, parties can securely exchange messages over untrusted channels. However, it's
crucial to use sufficiently large key sizes to prevent brute-force attacks.
EXPERIMENT-3

AIM: Implementation of Diffie Hellman Key Exchange Algorithm.

Theory

The Diffie-Hellman algorithm is being used to establish a shared secret that can be used for
secret communications while exchanging data over a public network using the elliptic curve to
generate points and get the secret key using the parameters.

For the sake of simplicity and practical implementation of the algorithm, we will consider only
4 variables, one prime P and G (a primitive root of P) and two private values a and b.

P and G are both publicly available numbers. Users (say Alice and Bob) pick private values a
and b and they generate a key and exchange it publicly. The opposite person receives the key
and that generates a secret key, after which they have the same secret key to encrypt.

Example

Step 1: Alice and Bob get public numbers P = 23, G = 9

Step 2: Alice selected a private key a = 4 and

Bob selected a private key b = 3

Step 3: Alice and Bob compute public values

Alice: x =(9^4 mod 23) = (6561 mod 23) = 6

Bob: y = (9^3 mod 23) = (729 mod 23)= 16

Step 4: Alice and Bob exchange public numbers

Step 5: Alice receives public key y =16 and

Bob receives public key x = 6

Step 6: Alice and Bob compute symmetric keys


Alice: ka = y^a mod p = 65536 mod 23 = 9

Bob: kb = x^b mod p = 216 mod 23 = 9

Step 7: 9 is the shared secret.


Code:
def prime_checker(p):

# Checks If the number entered is a Prime Number or not if p < 1:


return -1 elif p > 1:
if p == 2:

return 1

for i in range(2, p): if p % i == 0:


return -1

return 1

def primitive_check(g, p, L):

# Checks If The Entered Number Is A Primitive Root Or Not for i in range(1, p):
L.append(pow(g, i) % p) for i in range(1, p):
if L.count(i) > 1: L.clear()
l = []
return -1

return 1
while 1:

P = int(input("Enter P : ")) if prime_checker(P) == -1:


print("Number Is Not Prime, Please Enter Again!") continue
break while 1:
G = int(input(f"Enter The Primitive Root Of {P} : ")) if primitive_check(G, P, l) == -1:
print(f"Number Is Not A Primitive Root Of {P}, Please Try Again!") continue
break

# Private Keys

x1, x2 = int(input("Enter The Private Key Of User 1 : ")), int( input("Enter The Private Key Of User 2 : "))
while 1:

if x1 >= P or x2 >= P:

print(f"Private Key Of Both The Users Should Be Less Than {P}!") continue
break
# Calculate Public Keys
y1, y2 = pow(G, x1) % P, pow(G, x2) % P # Generate Secret Keys
k1, k2 = pow(y2, x1) % P, pow(y1, x2) % P

print(f"\nSecret Key For User 1 Is {k1}\nSecret Key For User 2 Is {k2}\n") if k1 == k2:
print("Keys Have Been Exchanged Successfully") else:
print("Keys Have Not Been Exchanged Successfully"
Output:

Conclusion:
We have successfully implemented the Diffie-Hillman algorithm.
Experiment 4

Aim : To implement digital signature scheme using elgamal theory

Theory :

The ElGamal Digital Signature Scheme is a public key cryptographic algorithm


used for generating and verifying digital signatures. It is based on the principles
of the ElGamal encryption system and the discrete logarithm problem.

The ElGamal Digital Signature Scheme uses a fixed-size hash function to


produce a message digest, which is then used to generate and verify digital
signatures. The private key is used to sign the message, and the public key is
used to verify the signature.

The ElGamal Digital Signature Scheme provides several advantages over other
digital signature algorithms. It is relatively easy to implement and provides a high
level of security against attacks, including forgery, tampering, and impersonation.
Additionally, the algorithm provides a high level of key security, as the private key
is never transmitted or shared.

However, the ElGamal Digital Signature Scheme also has limitations. It is


computationally intensive and requires large key sizes to ensure security.
Additionally, it is vulnerable to certain attacks, such as key compromise and
side-channel attacks.

Overall, the ElGamal Digital Signature Scheme is an important cryptographic tool


for secure digital communication and transactions. Its efficient and secure nature
has made it a popular choice for digital signature applications.
Experiment 4

Elgamal Algorithm :

The ElGamal Digital Signature Scheme involves the following steps for
generating and verifying digital signatures:
1. Key Generation: A user generates a public key and a private key. The public
key consists of the values p, g, and y, where p is a large prime number, g is a
generator of the multiplicative group modulo p, and y = g^x mod p, where x is the
private key.

2. Signing: To sign a message M, the signer performs the following steps:


a. Generate a random number k such that 1 < k < p-1.
b. Calculate r = g^k mod p.
c. Calculate h = hash(M), where hash is a fixed-size hash function. d. Calculate s
= (h — xr) * k^-1 mod (p-1).
e. The signature of the message M is the pair (r, s).

3. Verifying: To verify the signature (r, s) of a message M, the verifier performs


the following steps:
a. Verify that 1 < r < p-1 and 0 < s < p-1. If either condition is not satisfied, the
signature is invalid.
b. Calculate h = hash(M).
c. Calculate v1 = (y^r * r^s) mod p.
d. Calculate v2 = g^h mod p.
e. If v1 = v2, the signature is valid. Otherwise, the signature is invalid.

Code :
import java.math.BigInteger;
import java.util.Scanner;
import java.security.SecureRandom;

class ElGamal {
Experiment 4

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.println("Enter a large prime number (p): ");


BigInteger p = scanner.nextBigInteger();

System.out.println("Enter the public key (e1): ");


BigInteger e1 = scanner.nextBigInteger();

System.out.println("Enter the private key (d): ");


BigInteger d = scanner.nextBigInteger();

BigInteger l1 = e1.modPow(d, p);

System.out.println("\nPublic key: (" + e1 + ", " + l1 + ", " + p +


")");
System.out.println("Private key: " + d);

System.out.println("\nEnter the plain text (PT): ");


BigInteger plainText = scanner.nextBigInteger();

BigInteger r = getRandomInt(p.subtract(BigInteger.ONE));

BigInteger c1 = e1.modPow(r, p);

BigInteger c2 = plainText.multiply(l1.modPow(r, p)).mod(p);

System.out.println("\nCipher text: (" + c1 + ", " + c2 + ")");

BigInteger decryptedText = c2.multiply(c1.modPow(d.negate(),


p)).mod(p);
System.out.println("Decrypted text: " + decryptedText);
}
Experiment 4

private static BigInteger getRandomInt(BigInteger max) {


SecureRandom random = new SecureRandom();
BigInteger result;
do {
result = new
BigInteger(max.subtract(BigInteger.ONE).bitLength(), random);
} while (result.compareTo(BigInteger.ZERO) <= 0 ||
result.compareTo(max) >= 0);
return result;
}
}

Output :

Conclusion : Thus digit signature scheme using elgamal algorithm is


implemented
Experiment 4
Experiment-5
Aim : Implement MD-5 and SHA using python libraries
Theory : Cryptographic hashes are used in day-day life like in digital signatures, message
authentication codes, manipulation detection, fingerprints, checksums (message integrity
check), hash tables, password storage and much more. They are also used in sending
messages over network for security or storing messages in databases.
There are many hash functions defined in the “hashlib” library in python. This article deals
with explanation and working of MD5 hash.
This hash function accepts sequence of bytes and returns 128 bit hash value, usually used to
check data integrity but has security issues. Functions associated :

● encode() : Converts the string into bytes to be acceptable by hash function.

● digest() : Returns the encoded data in byte format.

● hexdigest() : Returns the encoded data in hexadecimal format.


This article deals with explanation and working of MD5 hash. This hash function accepts
sequence of bytes and returns 128 bit hash value, usually used to check data integrity but has
security issues. Functions associated : encode() : Converts the string into bytes to be
acceptable by hash function.

While all these functions serve the same basic purpose – to create a hash of data – they each
have their advantages and potential pitfalls.

● MD5: md5 is a widely used hash function that produces a 128-bit hash value. It’s
commonly used for checksums and data integrity. However, md5 is considered to be
broken in terms of collision resistance, which means it’s possible for two different
inputs to produce the same hash. Therefore, it’s not recommended for functions where
security is critical.

● SHA1: sha1 produces a 160-bit hash value, making it stronger than md5. However,
sha1 is also considered to be broken in terms of collision resistance and is no longer
recommended for functions where security is critical.

● SHA256: sha256 is part of the SHA-2 family of cryptographic hash functions and is
widely used in security applications and protocols. It produces a 256-bit hash value
and is currently considered to be secure against collision attacks.
Code :

import hashlib

data = 'Hello, World!'

# MD5

md5_hash = hashlib.md5(data.encode())

print('MD5:', md5_hash.hexdigest())

# SHA1

sha1_hash = hashlib.sha1(data.encode())

print('SHA1:', sha1_hash.hexdigest())

# SHA256

sha256_hash = hashlib.sha256(data.encode())

print('SHA256:', sha256_hash.hexdigest())

Output:

Conclusion: We have successfully implemented the MD-5 and SHA using python libraries.
AIM: Study the use of network reconnaissance tools like WHOIS, dig,traceroute, nslookup
to gather information about networks and domain registrars.

1. ipconfig
Displays all current TCP/IP network configuration values and refreshes Dynamic Host
Configuration Protocol (DHCP) and Domain Name System (DNS) settings. Used without
parameters, ipconfig displays Internet Protocol version 4 (IPv4) and IPv6 addresses, subnet
mask, and default gateway for all adapters.

2. nslookup
Displays information that you can use to diagnose Domain Name System (DNS) infrastructure.
Before using this tool, you should be familiar with how DNS works. The nslookup
command-line tool is available only if you have installed the TCP/IP protocol.

3. ping

Verifies IP-level connectivity to another TCP/IP computer by sending Internet Control Message
Protocol (ICMP) echo Request messages. The receipt of the corresponding echo Reply messages
is displayed, along with round-trip times. ping is the primary TCP/IP command used to
troubleshoot connectivity, reachability, and name resolution. Used without parameters, this
command displays Help content.

You can also use this command to test both the computer name and the IP address of the
computer. If pinging the IP address is successful, but pinging the computer name isn't, you might
have a name resolution problem. In this case, make sure the computer name you're specifying
can be resolved through the local Hosts file, by using Domain Name System (DNS) queries, or
through NetBIOS name resolution techniques.
4. hostname
Displays the host name portion of the full computer name of the computer.

5. tracert

This diagnostic tool determines the path taken to a destination by sending Internet Control
Message Protocol (ICMP) echo Request or ICMPv6 messages to the destination with
incrementally increasing time to live (TTL) field values. Each router along the path is required to
decrement the TTL in an IP packet by at least 1 before forwarding it. Effectively, the TTL is a
maximum link counter. When the TTL on a packet reaches 0, the router is expected to return an
ICMP time Exceeded message to the source computer.

This command determines the path by sending the first echo Request message with a TTL of 1
and incrementing the TTL by 1 on each subsequent transmission until the target responds or the
maximum number of hops is reached. The maximum number of hops is 30 by default and can be
specified using the /h parameter.
6. systeminfo
Displays detailed configuration information about a computer and its operating system, including
operating system configuration, security information, product ID, and hardware properties (such
as RAM, disk space, and network cards).
7. netstat
Displays active TCP connections, ports on which the computer is listening, Ethernet statistics,
the IP routing table, IPv4 statistics (for the IP, ICMP, TCP, and UDP protocols), and IPv6
statistics (for the IPv6, ICMPv6, TCP over IPv6, and UDP over IPv6 protocols). Used without
parameters, this command displays active TCP connections.
8. getmac
Returns the media access control (MAC) address and list of network protocols associated with
each address for all network cards in each computer, either locally or across a network. This
command is particularly useful either when you want to enter the MAC address into a network
analyzer, or when you need to know what protocols are currently in use on each network adapter
on a computer.

9. arp
Displays and modifies entries in the Address Resolution Protocol (ARP) cache. The ARP cache
contains one or more tables that are used to store IP addresses and their resolved Ethernet or
Token Ring physical addresses. There is a separate table for each Ethernet or Token Ring
network adapter installed on your computer. Used without parameters, arp displays help
information.
10. pathping
Provides information about network latency and network loss at intermediate hops between a
source and destination. This command sends multiple echo Request messages to each router
between a source and destination, over a period of time, and then computes results based on the
packets returned from each router. Because this command displays the degree of packet loss at
any given router or link, you can determine which routers or subnets might be having network
problems. Used without parameters, this command displays help.

11. ipconfig /displaydns


/displaydns Displays the contents of the DNS client resolver cache, which includes both
entries preloaded from the local Hosts file and any recently obtained resource
records for name queries resolved by the computer. The DNS Client service uses
this information to resolve frequently queried names quickly, before querying its
configured DNS servers.

12.ipconfig /flushdns
/flushdns Flushes and resets the contents of the DNS client resolver cache. During DNS
troubleshooting, you can use this procedure to discard negative cache entries from
the cache, as well as any other entries that have been added dynamically.
13. netstat -a
-a Displays all active TCP connections and the TCP and UDP ports on which
the computer is listening.

CONCLUSION: Hence, we have successfully implemented the commands.


Experiment - 7

Aim : To download and install nmap tool, use it with different scan options like
TCP scan, port scan, ping scan

Theory : Nmap (Network Mapper):

Definition:
Nmap, short for Network Mapper, is a powerful open-source tool designed for
network discovery and security auditing. It is used to scan and map networks,
identifying hosts, services, open ports, and other essential information. Nmap
employs a variety of scanning techniques to gather data about networked devices,
helping both network administrators and security professionals understand the
topology and vulnerabilities of a network.

Uses:
1. Network Discovery: Nmap can be employed to discover devices on a network,
providing a comprehensive list of active hosts and their IP addresses.

2. Port Scanning: One of the primary functions of Nmap is to perform port scans. It
identifies open, closed, and filtered ports on target systems, aiding in the
assessment of network security.

3. Service Version Detection: Nmap is capable of identifying the versions of services


running on open ports. This information is crucial for understanding potential
vulnerabilities associated with specific software versions.

4. Operating System Fingerprinting: Nmap can attempt to determine the operating


system of a target based on various characteristics observed during the scan. This
helps in creating a profile of the network environment.

5. Vulnerability Assessment: Security professionals use Nmap to identify potential


vulnerabilities on a network. By understanding the services and versions in use,
administrators can take proactive measures to secure their systems.

6. Scripting Engine: Nmap includes a scripting engine that allows users to run
custom scripts, enabling additional functionality for tasks like advanced service
detection, vulnerability scanning, and more.

Commands:
1. Ping Scan : In a ping scan, ICMP Echo Requests are used to check the online
status of a host. The process involves sending an ICMP (Internet Control
Message Protocol) Echo Request packet to the target host, and if the host is
online, it should respond with an ICMP Echo Reply.

2. Syn Scan (Half-open Scan) (-sS):


Description: It sends SYN packets to the target ports and listens for SYN-ACK
responses. It doesn't complete the TCP handshake.

3. UDP Scan (-sU):


Description: It is used to scan for open UDP ports on a target. UDP is a
connectionless protocol, and the scan sends UDP packets to the specified
ports.
4. OS Fingerprinting (-O):
Description: It tries to identify the operating system of the target.

5. ACK Scan (-sA):


Description: It sends ACK packets to determine if the ports are filtered or
unfiltered by the firewall.

6. TCP port scan:


To perform both TCP we use the -p option to specify the ports you want to
scan and the -sS option for TCP scanning . The -p 1-1000 option specifies
that you want to scan ports 1 through 1000. The -sS option specifies a TCP
SYN scan, which is a common and fast method for scanning open TCP ports.
7. Window Scan (-sW):
Description: It uses the TCP window field to differentiate between open and
closed ports.

8. Version Detection (-sV):


Description: It attempts to determine the version of services running on open
ports.
9. -top ports:
Using “–top-ports” parameter along with a specific number lets you scan the top X most
common ports for that host, as we can see:

10. scanme.nmap.org:
This option scans all reserved TCP ports on the machine scanme.nmap.org .

Conclusion: We have successfully installed the nmap tool and implemented different
scan options.
EXPERIMENT-8

AIM: To download and install wireshark tools to study different network protocols.

THEORY: Wireshark, a network analysis tool formerly known as Ethereal, captures packets in
real time and displays them in human-readable format. Wireshark includes filters, color coding,
and other features that let you dig deep into network traffic and inspect individual packets.
Capturing Packets: After downloading and installing Wireshark, you can launch it and
double-click the name of a network interface under Capture to start capturing packets on that
interface. For example, if you want to capture traffic on your wireless network, click your
wireless interface.
As soon as you click the interface’s name, you’ll see the packets start to appear in real time.
Wireshark captures each packet sent to or from your system. If you have promiscuous mode
enabled—it’s enabled by default—you’ll also see all the other packets on the network instead of
only packets addressed to your network adapter. To check if promiscuous mode is enabled, click
Capture > Options and verify the “Enable promiscuous mode on all interfaces” checkbox is
activated at the bottom of this window. Click the red “Stop” button near the top left corner of the
window when you want to stop capturing traffic.

Color Coding
You’ll probably see packets highlighted in a variety of different colors. Wireshark uses
colors to help you identify the types of traffic at a glance. By default, light purple is TCP
traffic, light blue is UDP traffic, and black identifies packets with errors—for example, they
could have been delivered out of order.
To view exactly what the color codes mean, click View > Coloring Rules. You can also
customize and modify the coloring rules from here, if you like
Sample Captures
If there’s nothing interesting on your own network to inspect, Wireshark’s wiki has you
covered. The wiki contains a page of sample capture files that you can load and inspect.
Click File > Open in Wireshark and browse for your downloaded file to open one.
You can also save your own captures in Wireshark and open them later. Click File > Save
to save your captured packets
Filtering Packets
If you’re trying to inspect something specific, such as the traffic a program sends when
phoning home, it helps to close down all other applications using the network so you can
narrow down the traffic.
Still, you’ll likely have a large amount of packets to sift through. That’s where Wireshark’s
filters come in

Type “dns” and you’ll see only DNS packets.


When you start typing, Wireshark will help you autocomplete your filter
You can also click Analyze > Display Filters to choose a filter from among the default filters
included in Wireshark. From here, you can add your own custom filters and save them to
easily access them in the future
Another interesting thing you can do is right-click a packet and select Follow > TCP Stream.
You’ll see the full TCP conversation between the client and the server. You can also click
other protocols in the Follow menu to see the full conversations for other protocols, if
applicable.
Close the window and you’ll find a filter has been applied automatically. Wireshark is
showing you the packets that make up the conversation.
Inspecting Packets Click a packet to select it and you can dig down to view its details. You can
also create filters from here — just right-click one of the details and use the Apply as Filter
submenu to create a filter based on it.
I/O Graph for a Trace File : To open the “I/O Graph” in Wireshark go into the Wireshark and
click on Statistics→ I/O Graph menu or toolbar item.

CONCLUSION: In summary, the exploration of packet sniffing through Wireshark, alongside


the analysis of ARP packets and the TCP/IP layer, yielded valuable insights into network traffic
and protocol behaviors. Wireshark, as a powerful tool, facilitated the examination of packet data,
enabling the observation of network communication patterns and identifying potential security
vulnerabilities. Moreover, the analysis of ARP packets provided visibility into address resolution
processes, while delving into the TCP/IP layer enhanced comprehension of data transmission
across networks. Through this study, the combination of Wireshark and ARP/TCP/IP analysis
emerged as an effective approach for understanding network protocols, diagnosing issues, and
bolstering network security
EXPERIMENT-9

Aim: To study Nessus vulnerability scanning tool.

Theory:

Nessus is a widely used vulnerability scanning tool that helps identify security issues in
computer systems, networks, and applications. It works by scanning for known
vulnerabilities and misconfigurations, providing detailed reports to help prioritize and
remediate issues. Nessus uses a database of known vulnerabilities, which is regularly
updated, to identify potential weaknesses in systems. Its features include vulnerability
scanning, configuration assessment, and compliance checks, making it valuable for both
security professionals and system administrators in maintaining the security posture of their
environments.
Implementation:
Installing and running the software:
Running a basic network scan:
Running an advanced network scan:

Conclusion: Thus, we have successfully studied Nessus vulnerability scanning tool.


EXPERIMENT 10

Aim: Case Study on SNORT IDS tool.

Theory:
1. Detection Engine: Snort's detection engine is the core component responsible for
analyzing network traffic. It utilizes a variety of detection methods, including
signature-based detection, anomaly-based detection, and protocol analysis, to identify
potential security threats.

2. Rule-Based Detection: Snort uses a rule-based approach for intrusion detection, where
administrators define rules that specify patterns or characteristics of network traffic
indicative of malicious activity. These rules can be customized and tailored to match
the specific security requirements of the network environment.

3. Flexible Deployment: Snort can be deployed in different network configurations,


including inline mode for intrusion prevention and passive mode for intrusion
detection. It can also operate as a network-based IDS, inspecting traffic at the network
level, or as a host-based IDS, monitoring activity on individual hosts.

4. Alerting and Logging: When Snort detects suspicious activity that matches a defined
rule, it generates an alert and logs relevant information about the detected event.
Administrators can configure alerting mechanisms to notify them of potential security
incidents in real time, enabling timely response and mitigation.

5. Community Support: Snort benefits from a large and active user community,
contributing to the continuous development, improvement, and refinement of the tool.
The availability of community-contributed rules and plugins enhances Snort's
effectiveness and adaptability to evolving threats.

Conclusion:
Snort is a powerful and versatile intrusion detection and prevention tool that plays a crucial
role in safeguarding network security. Its rule-based detection engine, flexible deployment
options, and alerting capabilities make it well-suited for detecting and mitigating a wide
range of security threats. With its open-source nature and strong community support, Snort
continues to be a valuable asset for organizations seeking to enhance their network security
posture and protect against cyber threats.

You might also like