0% found this document useful (0 votes)
29 views12 pages

Cns Lab Manual 3-2 It

The document outlines various programming tasks related to cryptography and network security, including implementing algorithms like RC4, Blowfish, RSA, and Diffie-Hellman in Java and C. It also covers concepts such as XOR, AND, and OR operations on strings, as well as analyzing network security principles. The course aims to equip students with skills to understand and mitigate security threats in computer networks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views12 pages

Cns Lab Manual 3-2 It

The document outlines various programming tasks related to cryptography and network security, including implementing algorithms like RC4, Blowfish, RSA, and Diffie-Hellman in Java and C. It also covers concepts such as XOR, AND, and OR operations on strings, as well as analyzing network security principles. The course aims to equip students with skills to understand and mitigate security threats in computer networks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

IT3207 7.

7. Write the RC4 logic in Java Using Java cryptography; encrypt the text ‘Hello world’ using CRYPTOGRAPHY & NETWORK SECURITY LAB
Blowfish. Create your own key using Java key tool.
CRYPTOGRAPHY & NETWORK SECURITY LAB INDEX
8. Write a Java program to implement RSA algorithm.
Course objectives Cycle-1
9. Implement the Diffie-Hellman Key Exchange mechanism using HTML and JavaScript. Cryptography
After the success full completion of this course the student is enable towards learning and 10. Calculate the message digest of a text using the SHA-1 algorithm in JAVA. Page
[Link].
overcome security attacks in future Name of the Program No.
11. Calculate the message digest of a text using the MD5 algorithm in JAVA. Write a C program that contains a string (char pointer) with a value ‘Hello
Course outcomes 1 world’. The program should XOR each character in this string with 0 and 1
displays the result.
Cycle 2 - Network Security
Understand computer security principles and discuss ethical issues for theft of information. Write a C program that contains a string (char pointer) with a value ‘Hello
1. a) Find the IP address, MAC address of your machine. 2 world’. The program should AND or and XOR each character in this string with 3
Identify threat models and common computer network security goals.
127 and display the result.
b) Find the neighbouring machines in your network. Write a Java program to perform encryption and decryption using the
Explain various encryption algorithms, hashing functions, one-way authentication and public key following algorithms
c) Check if a server is up and running.
cryptology · 3 a) Ceaser cipher 5
2. Run tcpdump/windump utility with atleast 4 options. b) Substitution cipher
c) Hill Cipher
Analyze firewalls, DOS attacks and defense types. Dramatize example scenarios in DNS and 3. Capture the packets in your system using wireshark and analyse any one TCP packet Write a C/JAVA program to implement the DES algorithm logic.
4 17
IPSec applications in detail. 5 Write a C/JAVA program to implement the Blowfish algorithm logic. 22
6 Write a C/JAVA program to implement the Rijndael algorithm logic. 27
4. Use snort to detect intrusion packets. Write the RC4 logic in Java Using Java cryptography; encrypt the text ‘Hello
List of Experiments 7 30
5. Demonstrate ARP Poisoning. world’ using Blowfish. Create your own key using Java key tool.
Cycle 1 - Cryptography 8 Write a Java program to implement RSA algorithm. 32
Implement the Diffie-Hellman Key Exchange mechanism using HTML and
1. Write a C program that contains a string (char pointer) with a value ‘Hello world’. The 9 35
JavaScript.
program should XOR each character in this string with 0 and displays the result. 10 Calculate the message digest of a text using the SHA-1 algorithm in JAVA. 40
11 Calculate the message digest of a text using the MD5 algorithm in JAVA. 43
2. Write a C program that contains a string (char pointer) with a value ‘Hello world’. The
program should AND or and XOR each character in this string with 127 and display the Cycle-2
result. Network Security
3. Write a Java program to perform encryption and decryption using the following algorithms Page
[Link].
Name of the Program No.
Ceaser cipher a) Find the IP address, MAC address of your machine.
1 b) Find the neighbouring machines in your network. 46
Substitution cipher c) Check if a server is up and running.
Hill Cipher 2 Run tcpdump/windump utility with atleast 4 options. 51
Capture the packets in your system using wireshark and analyse any one TCP
3 54
4. Write a C/JAVA program to implement the DES algorithm logic. packet in detail.
4 Use snort to detect intrusion packets. 57
5. Write a C/JAVA program to implement the Blowfish algorithm logic.
5 Demonstrate ARP Poisoning. 60
6. Write a C/JAVA program to implement the Rijndael algorithm logic.

Cycle-1
Cryptography
1. AIM: Write a C program that contains a string (char pointer) with a value ‘Hello PROGRAM: 2. AIM: Write a C program that contains a string (char pointer) with a value ‘Hello World’.

world’. The program should XOR each character in this string with 0 and displays the #include<stdlib. The program should AND OR and XOR each character in this string with 127 and display
result. h> main() the result.

XOR a string with Zero: {


AND
XOR is a simple bitwise operation that allows cryptographers to create strong encryption char str[]="Hello World"; The AND operator is also known as logical conjunction, and works just like multiplication.
systems, and consequently is a fundamental building block of practically all modern ciphers. char str1[11]; It outputs a 1 only if all of the inputs are 1. Here is the truth table:
XOR, or “exclusive or” operates on binary data. It returns true if both of its inputs are int i, len; 0 AND 0 = 0
opposites (one false and one true), otherwise, it returns false. You may see the operator written len=strlen(str); 0 AND 1 = 0
this way: ⊕. for(i=0;i<len;i++) 1 AND 0 = 0
{
1 AND 1 = 1
str1[i]=str[i]^0; Let’s try it:
printf("%c",str1[i 100111001011010100111010 AND 010110100001101111011000 = 000110000001000100011000
]);
} OR
printf("\n"); The OR operator is also known as logical disjunction.
Understanding XOR with Zero
} It outputs a 1 whenever one or more of its inputs are 1. The truth table is

XOR with zero is a logical operation used in computer networks. It is a binary operation that takes 0 OR 0 = 0

two inputs and returns a single output. When one of the inputs is zero, the result of the operation is Output: Hello 0 OR 1 = 1
the same as the other input. World 1 OR 0 = 1
1 OR 1 = 1
In computer networks, XOR with zero is used to compare two values. If the two values are the
Let’s try it:
same, the result of the operation is zero. If the two values are different, the result of the operation is
100111001011010100111010 OR 010110100001101111011000 = 110111101011111111111010
one. This operation is used in many areas such as encryption, error detection, and data transmission.

XOR
The XOR operator outputs a 1 whenever the inputs do not match, which occurs when one of the two
inputs is exclusively true.
This is the same as addition mod 2. Here is the truth table:
0 XOR 0 = 0
0 XOR 1 = 1
1 XOR 0 = 1
1 XOR 1 = 0
Let's try it:
100111001011010100111010 XOR 010110100001101111011000 = 110001101010111011100010
III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 1 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 2
III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 3

PROGRAM: 3. AIM: Write a Java program to perform encryption and decryption using the following We use the following steps to implement the program for the Caesar Cipher technique:
#include<stdio.h> algorithms
#include<stdlib.h> a) Caeser Cipher 1. Take an input string from the user to encrypt it using the Caesar Cipher technique.
void main() 2. Take an input integer from the user for shifting characters. The input integer should be between
b) Substitution Cipher
{ 0-25.
c) Hill Cipher
char str[]="Hello World"; 3. Traverse input string one character at a time.
char str1[11]; a) Caeser Cipher
4. Depending on the encryption and decryption, we transform each character as per the rule.
char str2[11]=str[]; It is one of the simplest and most used encryption techniques. In this technique, each letter of the
5. Returns the newly generated string.
char str3[11]=str[]; given text is replaced by a letter of some fixed number of positions down the alphabet.
int i,len; For example, with a shift of 1, X would be replaced by Y, Y would become Z, and so on. PROGRAM:
len = strlen(str); An integer value is required to cipher a given text. The integer value is known as shift, which
import [Link];
indicates the number of positions each letter of the text has been moved down.
for(i=0;i<len;i++) {
import [Link];
str1[i] = str[i]&127;
import [Link];
printf("%c",str1[i]);
} import [Link];

printf("\n"); public class CaesarCipher {

for(i=0;i<len;i++) { static Scanner sc=new Scanner([Link]);

Str2[i] = str[i]|127; public static void main(String[] args) throws IOException


printf("%c",str2[i]);
{
}
[Link]("Enter any String: ");
printf("\n");
We can mathematically represent the encryption of a letter by a shift n in the following way:
String str=[Link]();
for(i=0;i<len;i++) {
str3[i] = str2[i]^127; Encryption phase with shift n = En (x) = (x+n) mod 26 [Link]("\nEnter the Key: ");

printf("%c",str3[i]); int key= [Link]();


Decryption phase with shift n = Dn (x) = (x-n) mod 26
}
String encrypted = encrypt(str, key);
printf("\n"); Example
} [Link]("\nEncrypted String is: " +encrypted);

Output: Text: ATTACKATONCE


String decrypted = decrypt(encrypted, key);
Hello World Shift: 4
[Link]("\nDecrypted String is: "+decrypted);
(../.. (Garbage Value)
Cipher: EXXEGOEXSRGI
)..... (Garbage Value) [Link]("\n");
III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 5 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 6
III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 4
} for(int i= 0; i < [Link](); i++)
b) Substitution Cipher
public static String encrypt(String str, int key) { Substitution encryption consists, as its name suggests, of substituting (replacing) one element
{ int c = [Link](i); with another. In the case of a text, it is a question of replacing the characters (often letters) of the
message by others.
String encrypted = ""; if ([Link](c))
Encryption of a letter by a shift n can be described mathematically as.
for(int i = 0; i < [Link](); i++) {
En (x) = (x + n) mod 26
{ c = c - (key % 26);
Decryption of a letter by a shift n can be described mathematically as.
int c = [Link](i); if (c < 'A')
Dn (x) = (x - n) mod 26
if ([Link](c)) { c = c + 26;
Hiding some data is known as encryption. When plain text is encrypted it becomes unreadable
c = c + (key % 26); } and is known as ciphertext. In a Substitution cipher, any character of plain text from the given fixed set
if (c > 'Z') else if ([Link](c)) of characters is substituted by some other character from the same set depending on a key.
Special case of Substitution cipher is known as Caesar Cipher
c = c - 26; {
Algorithm for Substitution Cipher:
} c = c - (key % 26); Input:
else if([Link](c)) { if (c < 'a')  A String of both lower and upper case letters, called Plain Text.
 An Integer denoting the required key.
c = c + (key % 26); c= c+26;
Procedure:
if (c > 'z') }  Create a list of all the characters.

c = c - 26; decrypted += (char) c;  Create a dictionary to store the substitution for all characters.
 For each character, transform the given character as per the rule, depending on whether
} }
we’re encrypting or decrypting the text.
encrypted += (char) c; return decrypted;  Print the new string generated.

} } PROGRAM:

return encrypted; } import [Link];

} Output: import [Link];

public static String decrypt(String str, int key) Enter any String: Hello World import [Link];
Enter the Key: 5
{ import [Link];
Encrypted String is: Mjqqt Btwqi
String decrypted = ""; Decrypted String is: Hello World public class SubCipher {

III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 7 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 8 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 9

static Scanner sc = new Scanner([Link]); Output: c) Hill Cipher

static BufferedReader br = new BufferedReader(new InputStreamReader([Link])); Enter any string: hello Hill cipher is a polygraphic substitution cipher based on linear [Link] letter is

public static void main(String[] args) throws IOException { Encrypted data is: svool represented by a number modulo 26. Often the simple scheme A = 0, B = 1, …, Z = 25 is used,
but this is not an essential feature of the cipher. To encrypt a message, each block of n letters
String a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; Decrypted data is: hell
(considered as an n-component vector) is multiplied by an invertible n × n matrix, against
String b = "zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA"; modulus 26. To decrypt the message, each block is multiplied by the inverse of the matrix used
[Link]("Enter any string: "); for encryption. The matrix used for encryption is the cipher key, and it should be chosen
randomly from the set of invertible n × n matrices (modulo 26).
String str = [Link]();

String encrypt = ""; PROGRAM:


import [Link].*;
String decrypt = "";
import [Link];
char c; public class HC

for(int i=0;i<[Link]();i++) { {
public static void getKey(String inputKey, int key[][])
c = [Link](i);
{
int j = [Link](c); int k = 0;
encrypt = encrypt+[Link](j); for(int i = 0; i < 3; i++)
{
}
for(int j = 0; j < 3; j++)
[Link]("Encrypted data is: " +encrypt); {
for(int i=0;i<[Link]();i++) { key[i][j] = ([Link](k)) % 65;
k++;
c = [Link](i);
}
int j = [Link](c);
}
decrypt = decrypt+[Link](j); }
public static void encrypt(int mat[][], int key[][], int msgVector[][])
}
{
[Link]("Decrypted data is: " +decrypt);
int x, i, j;
} for(i = 0; i < 3; i++)

} {
for(j = 0; j < 1; j++)

III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 10 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 11 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 12
{ } for(x = 0; x < 3; x++)
mat[i][j] = 0; } decry[i][0] += inverse[i][x] * mat[x][0];
[Link]("Adjoint Matrix: "); decry[i][0] = decry[i][0] % 26;
for(x = 0; x < 3; x++) for(i = 0; i < 3; i++) }
mat[i][j] += key[i][x] * msgVector[x][j]; { String decryptedText = " ";
mat[i][j] = mat[i][j] % 26; for(j = 0; j < 3; j++) for(int p = 0; p < 3; p++)
} [Link](adj[i][j]); decryptedText += (char)(decry[p][0] + 65);
} } [Link]("\nDecrypted Text : " +decryptedText);
} for(i = 0; i < 26; i++) }
public static void decrypt(int mat[][], int key[][]) { public static void HillCipher(String msg, String inputKey)
{ if(((det*i) % 26) == 1) {
int i, j, x; { int [][]key = new int[3][3];
int det = 0; inverseOfDet = i; getKey(inputKey, key);
int inverseOfDet = 0; break; int [][]msgVector = new int[3][1];
int [][]inverse = new int[3][3]; } for(int i = 0; i < 3; i++)
int [][]adj = new int[3][3]; } msgVector[i][0] = ([Link](i)) % 65;
int [][]decry = new int[3][1]; [Link]("Inverse of det = " +inverseOfDet); int [][]mat = new int[3][1];
for(i = 0; i < 3; i++) for(i = 0; i < 3; i++) encrypt(mat, key, msgVector);
det = det + (key[0][i] * (key[1][(i+1)%3] * key[2][(i+2)%3] - key[1][(i+2)%3] * { String CipherText = " ";
key[2][(i+1)%3])); for(j = 0; j < 3; j++) for(int i = 0; i < 3; i++)
det = det % 26; inverse[i][j] = (inverseOfDet * adj[i][j]) % 26; CipherText += (char)(mat[i][0] + 65);
if(det < 0) } [Link]("\nCipherText: " +CipherText);
det = 26 + det; [Link]("\nInverse matrix: "); for(int i = 0; i < 3; i++)
[Link]("\n det = " +det); for(i = 0; i < 3; i++) [Link](mat[i][0]);
for(i = 0; i < 3; i++) { decrypt(mat, key);
{ for(j = 0; j < 3; j++) }
for(j = 0; j < 3; j++) { public static void main(String args[])
{ [Link](inverse[i][j]); {
adj[i][j] = ((key[(j+1)%3][(i+1)%3] * key[(j+2)%3][(i+2)%3]) - (key[(j+1)%3][(i+2)%3] * } String msg = new String();
key[(j+2)%3][(i+1)%3])); } String inputKey = new String();
adj[i][j] = adj[i][j] % 26; for(i = 0; i < 3; i++) Scanner sc = new Scanner([Link]);
if(adj[i][j] < 0) { [Link](" Enter the message of size 3: ");
adj[i][j] = 26 + adj[i][j]; decry[i][0] = 0; msg = [Link]();
III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 13 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 14 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 15

[Link]("Enter the key of size 9: ");


inputKey = [Link](); 4. AIM: Write a C/JAVA program to implement the DES algorithm logic.
HillCipher([Link](), [Link]()); DES stands for Data Encryption Standard. There are certain machines that can be used to crack PROGRAM:
}
the DES algorithm. The DES algorithm uses a key of 56-bit size. Using this key, the DES takes a block import [Link].*;
}
of 64-bit plain text as input and generates a block of 64-bit cipher text. import [Link].Base64;

Output: The DES process has several steps involved in it, where each step is called a round. Depending import [Link];

Enter the message of size 3: ACT upon the size of the key being used, the number of rounds varies. For example, a 128-bit key requires import [Link];

Enter the key of size 9: 10 rounds, a 192-bit key requires 12 rounds, and so on. import [Link];
GYBNQKURP import [Link];
DES Algorithm Steps
CipherText: POH import [Link];
To put it in simple terms, DES takes 64-bit plain text and turns it into a 64-bit ciphertext. And since
Decrypted Text: ACT import [Link];
we’re talking about asymmetric algorithms, the same key is used when it’s time to decrypt the text.

The algorithm process breaks down into the following steps: import [Link];

public class DESalgorithm {


1. The process begins with the 64-bit plain text block getting handed over to an initial permutation (IP)
private static final String UNICODE_FORMAT = "UTF8";
function.
public static final String DES_ENCRYPTION_SCHEME = "DES";
2. The initial permutation (IP) is then performed on the plain text.
private KeySpec myKeySpec;
3. Next, the initial permutation (IP) creates two halves of the permuted block, referred to as Left Plain
private SecretKeyFactory mySecretKeyFactory;
Text (LPT) and Right Plain Text (RPT).
private Cipher cipher;
4. Each LPT and RPT goes through 16 rounds of the encryption process.
byte[] keyAsBytes;
5. Finally, the LPT and RPT are rejoined, and a Final Permutation (FP) is performed on the newly
private String myEncryptionKey;
combined block.
private String myEncryptionScheme;
6. The result of this process produces the desired 64-bit ciphertext.
SecretKey key;

static BufferedReader br = new BufferedReader(new


InputStreamReader([Link]));

public DESalgorithm() throws Exception {

myEncryptionKey = "ThisIsSecretEncryptionKey";

III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 16 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 17 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 18
myEncryptionScheme = DES_ENCRYPTION_SCHEME; public String decrypt(String encryptedString) {

keyAsBytes = [Link](UNICODE_FORMAT); { [Link]("Enter the string: ");

myKeySpec = new DESKeySpec(keyAsBytes); String decryptedText=null; DESalgorithm myEncryptor= new DESalgorithm();

mySecretKeyFactory = try String stringToEncrypt = [Link]();


[Link](myEncryptionScheme);
{ String encrypted = [Link](stringToEncrypt);
cipher = [Link](myEncryptionScheme);
[Link](Cipher.DECRYPT_MODE, key); String decrypted = [Link](encrypted);
key = [Link](myKeySpec);
[Link] base64decoder = [Link](); [Link]("\nString To Encrypt: "+stringToEncrypt);
}
byte[] encryptedText = [Link](encryptedString); [Link]("\nEncrypted Value: " +encrypted);
public String encrypt(String unencryptedString)
byte[] plainText = [Link](encryptedText); [Link]("\nDecrypted String: " +decrypted);
{
decryptedText=bytes2String(plainText); }
String encryptedString = null;
} }
try
catch (Exception e) {
{ OUTPUT:
[Link](); }
[Link](Cipher.ENCRYPT_MODE, key);
return decryptedText; Enter the string: Welcome
byte[] plainText = [Link](UNICODE_FORMAT);
} String t o Encrypt: Welcome
byte[] encryptedText = [Link](plainText);
private static String bytes2String(byte[] bytes) Encrypted Value: u0eMFI6wgMc=
[Link] base64encoder = [Link]();
{ Decrypted String: Welcome
encryptedString = [Link](encryptedText);
StringBuffer stringBuffer = new StringBuffer();
}
for (int i = 0; i <[Link];i++) {
catch (Exception e)
[Link]((char) bytes[i]);
{
}
[Link]();
return [Link]();
}
}
return encryptedString;
public static void main(String args []) throws Exception
}
III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 19 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 20 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 21

String inputMessage,encryptedData,decryptedMessage; String knum = [Link](num);


5. AIM: Write a C/JAVA program to implement the BlowFish algorithm logic.
byte[] knumb = [Link]();
Blowfish features a 64-bit block size and takes a variable-length key, from 32 bits to 448 bits. It
consists of 16 Feistel-like iterations, where each iteration operates on a 64-bit block that's split into two public Blowfish() { skey=getRawKey(knumb);

32-bit words. Blowfish uses a single encryption key to both encrypt and decrypt data. try { skeyString = new String(skey);

The Blowfish algorithm consists of two major parts: generateSymmetricKey(); [Link]("Blowfish Symmetric key = "+skeyString);

inputMessage=[Link](null,"Enter message to encrypt"); }


1. Data encryption: Data encryption happens through a 16-round Feistel network, with each round
consisting of a key-dependent permutation and a key- and data-dependent substitution. Large, key- byte[] ibyte = [Link](); catch(Exception e) {
dependent S-boxes work with the substitution method and form an integral part of the data
byte[] ebyte=encrypt(raw, ibyte); [Link](e);
encryption system in Blowfish. All encryption operations are XORs -- a type of logic gate -- and
String encryptedData = new String(ebyte); }
additions on 32-bit words.
[Link]("Encrypted message "+encryptedData); }
2. Key expansion and subkeys: In the key expansion process, maximum size 448-bit keys are
converted into several subkey arrays totaling 4,168 bytes. Subkeys form an integral part of the [Link](null,"Encrypted Data "+"\n"+encryptedData); private static byte[] getRawKey(byte[] seed) throws Exception {
Blowfish algorithm, which uses a large number of them. These subkeys are pre-computed
byte[] dbyte= decrypt(raw,ebyte); KeyGenerator kgen = [Link]("Blowfish");
before encryption or decryption can take place.
String decryptedMessage = new String(dbyte); SecureRandom sr = [Link]("SHA1PRNG");
PROGRAM:
[Link]("Decrypted message "+decryptedMessage); [Link](seed);
import [Link].*;
[Link](null,"Decrypted Data "+"\n"+decryptedMessage); [Link](128, sr); // 128, 256 and 448 bits may not be available
import [Link];
} SecretKey skey = [Link]();
import [Link];
catch(Exception e) { raw = [Link]();
import [Link];
[Link](e); return raw;
import [Link];
} }
import [Link];
} private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
import [Link] ;
void generateSymmetricKey() { SecretKeySpec skeySpec = new SecretKeySpec(raw, "Blowfish");
class Blowfish {
try { Cipher cipher = [Link]("Blowfish");
byte[] skey = new byte[1000];
Random r = new Random(); [Link](Cipher.ENCRYPT_MODE, skeySpec);
String skeyString;
int num = [Link](10000); byte[] encrypted = [Link](clear);
static byte[] raw;

III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 22 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 23 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 24
return encrypted;
6. AIM: Write a C/JAVA program to implement the Rijndael algorithm logic.
}
Rijndael is an Advanced Encryption Standard (AES) algorithm. It replaced the older and
private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
weaker Data Encryption Standard (DES) when it was selected as the standard symmetric
SecretKeySpec skeySpec = new SecretKeySpec(raw, "Blowfish"); key encryption algorithm by the National Institute of Standards and Technology (NIST).

Cipher cipher = [Link]("Blowfish"); Rijndael is an iterated block cipher, meaning that it encrypts and decrypts a block of data by the
[Link](Cipher.DECRYPT_MODE, skeySpec); iteration or round of a specific transformation. It supports encryption key sizes of 128, 192, and 256
bits and handles data in 128-bit blocks.
byte[] decrypted = [Link](encrypted);

return decrypted;
Working of Rijndael
}
In Rijndael, encryption happens through a series of matrix transformations or rounds. The number
public static void main(String args[]) { of rounds are variable, depending on the key or block sizes used:

Blowfish blwfish = new Blowfish();


 128 bits = 9 rounds
}
 192 bits = 11 rounds
}
 256 bits = 13 rounds
OUTPUT:
The Rijndael algorithm is based on byte-by-byte replacement, swap and XOR operations. The
procedure is as follows:

 The algorithm generates 10 128-bit keys from the 128-bit key, which are stored in 4x4 tables.

 The plaintext is divided into 4x4 tables, each of 128-bit sizes.

 Each 128-bit plaintext piece goes through a variable number of rounds as mentioned above. The
code is generated after the 10th round.

Each round consists of four steps:

1. Byte Sub. Each byte of the block is replaced by its substitute in the S-box.

2. Shift Row. In a block made of bytes 1 to 16, bytes are arranged in a rectangle and shifted
according to block sizes.

III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 25 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 26 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 27

SecretKey skey =[Link](); 7. AIM: Write the RC4 logic in Java Using Java cryptography; encrypt the text ‘Hello
3. Mix Column. Here, matrix multiplication is performed, where each column is multiplied by the
matrix. The bytes being multiplied are treated as polynomials, not as numbers. When results have byte[] raw= [Link](); world’ using Blowfish. Create your own key using Java key tool.

more than 8 bits, the extra bits are cancelled out by XORing the binary 9-bit string 100011011 with SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); RC4: This algorithm is used to create pseudo-random stream of bits (a key-stream). As with
the result. This technique is similar to what is used in in cyclic redundancy checks. // Instantiate the cipher any stream cipher, keystreams can be used for encryption.
Cipher cipher = [Link]("AES");
4. Add Round Key. Here, the subkey for the current round is XORed. A stream cipher is a symmetric key cipher where plaintext digits one at a time are XORed
[Link](Cipher.ENCRYPT_MODE, skeySpec);
with corresponding digits of pseudorandom stream of bits(keystream) to create encrypted
byte[] encrypted = [Link](([Link] == 0 ? message :args[0]).getBytes());
message i.e. cipher text.
PROGRAM: [Link]("Encrypted string: " + asHex(encrypted));
import [Link].*; RC4 is mostly used in protocols such as
[Link](Cipher.DECRYPT_MODE, skeySpec);
import [Link].*; byte[] original = [Link](encrypted); 1)Secure Socket Layer (SSL) to establish an encrypted link between a webserver and a
import [Link].*; String originalString = new String(original); browser to ensure all data transmitted remain private and generally used by many websites to
import [Link].*; [Link]("Decrypted string: " + originalString + " " + asHex(original)); protect their online transaction with their customers
public class AES { } 2) Wired Equivalent Privacy (WEP) security protocol to provide security and privacy to
public static String asHex (byte buf[]) { } wireless networks (e.g. Wi-Fi) comparable to as in Wired Network(LAN)
StringBuffer strbuf = new StringBuffer([Link] * 2);
int i; OUTPUT:
PROGRAM:
for (i = 0; i < [Link]; i++) {
import [Link];
if (((int) buf[i] & 0xff) < 0x10)
import [Link];
[Link]("0");
import [Link];
[Link]([Link]((int) buf[i] & 0xff, 16));
import [Link];
}
public class RC4 {
return [Link]();
public static void main(String[] args) throws Exception {
}
public static void main(String[] args) throws Exception // create a key generator based upon the Blowfish cipher

{ KeyGenerator keygenerator = [Link]("Blowfish");

String message="Cryptography Lab"; // create a key

[Link]("Entered String: " + message); SecretKey secretkey = [Link]();

// Get the KeyGenerator // create a cipher based upon Blowfish

KeyGenerator kgen = [Link]("AES"); Cipher cipher = [Link]("Blowfish");

[Link](128); // 192 and 256 bits may not be available // initialise cipher to with secret key

// Generate the secret key [Link](Cipher.ENCRYPT_MODE, secretkey);

III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 28 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 29 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 30
// get the text to encrypt 8. AIM: Write a Java program to implement RSA Algorithm. PROGRAM:
String inputText = [Link]("Input your message: "); RSA is an algorithm used by modern computers to encrypt and decrypt messages. It is an asymmetric
import [Link];
cryptographic algorithm. Asymmetric means that there are two different keys. This is also called public key
cryptography, because one of them can be given to everyone. A basic principle behind RSA is the observation import [Link];
// encrypt message
that it is practical to find three very large positive integers e, d and n such that with modular exponentiation for import [Link].*;
byte[] encrypted = [Link]([Link]());
all integer m:
// re-initialise the cipher to be in decrypt mode import [Link]; import [Link];
(m ) = m (mod n)
e d

[Link](Cipher.DECRYPT_MODE, secretkey);
The public key is represented by the integers n and e; and, the private key, by the integer public class RSA{
// decrypt message
d. m represents the message. RSA involves a public key and a private key. The public key can be known by static Scanner sc = new Scanner([Link]);
byte[] decrypted = [Link](encrypted);
everyone and is used for encrypting messages. The intention is that messages encrypted with the public key can
// and display the results public static void main(String[] args) {
only be decrypted in a reasonable amount of time using the private key.
[Link]([Link](), "\nEncrypted text: " + new
[Link]("Enter a Prime number: ");
String(encrypted) + "\n" + "\nDecrypted text: " + new String(decrypted));
BigInteger p = [Link]();
[Link](0);
}} [Link]("Enter another prime number: ");

OUTPUT: BigInteger q = [Link]();

BigInteger n = [Link](q);

BigInteger n2 = [Link]([Link]).multiply([Link]([Link]));

BigInteger e= generateE(n2);

BigInteger d = [Link](n2); // Here's the multiplicative inverse

[Link]("Encryption keys are: " + e + ", " + n);

[Link]("Decryption keys are: " + d + ", " + n);

public static BigInteger generateE(BigInteger fiofn) {

int y, GCD;

BigInteger e;

BigInteger gcd;

Random x = new Random();

III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 31 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 32 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 33

do STEP-6: Now both of them compute their common secret key as the other one’s secret key power of a
09. AIM: Implement the Diffie-Hellman Key Exchange mechanism using HTML and
mod p.
{ JavaScript. Consider the end user as one of the parties (Alice) and the JavaScript application as
PROGRAM:
y = [Link]([Link]()-1); other party (bob).
<!DOCTYPE html>
String z = [Link](y); Diffie–Hellman Key Exchange establishes a shared secret between two parties that can be used for <html>
secret communication for exchanging data over a public network. It is primarily used as a method of <head>
e = new BigInteger(z);
exchanging cryptography keys for use in symmetric encryption algorithms like AES. The algorithm in itself <title>Diffie-Hellman Key Exchange Mechanism</title>
gcd = [Link](e); is very simple. The process begins by having the two parties, Alice and Bob. Let's assume that Alice wants to
</head>
establish a shared secret with Bob.
GCD = [Link](); <body>

} <center>
<h1>Diffie-Hellman Key Exchange Mechanism</h1>
while(y <= 2 || GCD != 1);
<label for="p">p (prime number):</label>
return e; <input type="text" id="p" name="p" value=""><br><br>

} <label for="g">g (primitive root of p):</label>


<input type="text" id="g" name="g" value=""><br><br>
}
<label for="a">a (Alice's private key):</label>
<input type="text" id="a" name="a" value=""><br><br>
OUTPUT: <label for="b">b (Bob's private key):</label>
Enter a Prime number: 5 <input type="text" id="b" name="b" value=""><br><br>
Enter another prime number: 11 <button onclick="generateKeys()">Generate Keys</button><br><br>
Encryption keys are: 33, 55 <label for="aliceKey">Alice's public key:</label>
Decryption keys are: 17, 55 <input type="text" id="aliceKey" name="aliceKey" value=""><br><br>
<label for="bobKey">Bob's public key:</label>
<input type="text" id="bobKey" name="bobKey" value=""><br><br>
<button onclick="generateSharedSecret()">Generate Shared Secret</button><br><br>
Algorithm:
<label for="sharedSecret">Shared secret:</label>
STEP-1: Both Alice and Bob shares the same public keys g and p.
<input type="text" id="sharedSecret" name="sharedSecret" value=""><br><br>
STEP-2: Alice selects a random public key a.
STEP-3: Alice computes his secret key A as ga mod p.
<script>
STEP-4: Then Alice sends A to Bob.
function generateKeys() {
STEP-5: Similarly, Bob also selects a public key b and computes his secret key as B and sends the same
// Retrieve input values
back to Alice.
let p = parseInt([Link]("p").value);
III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 34 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 35 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 36
let g = parseInt([Link]("g").value); result = (result * base) % modulus;
let a = parseInt([Link]("a").value); }
let b = parseInt([Link]("b").value); exponent = [Link](exponent / 2);
// Calculate public keys base = (base * base) % modulus;
let aliceKey = modExp(g, a, p); }
let bobKey = modExp(g, b, p); return result;
// Set output values }
[Link]("aliceKey").value = aliceKey; </script>
[Link]("bobKey").value = bobKey; </center>
} </body>
</html>
function generateSharedSecret() {
OUTPUT:
// Retrieve input values
let p = parseInt([Link]("p").value);
let a = parseInt([Link]("a").value);
let bobKey = parseInt([Link]("bobKey").value);

// Calculate shared secret


let sharedSecret = modExp(bobKey, a, p);

// Set output value


[Link]("sharedSecret").value = sharedSecret;
}
// Calculates (base ^ exponent) % modulus using the modular exponentiation algorithm
function modExp(base, exponent, modulus) {
if (modulus === 1) {
return 0;
}
let result = 1;
base = base % modulus;
while (exponent > 0) {
if (exponent % 2 === 1) {
III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 37 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 38 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 39

[Link]([Link]()); OUTPUT:
10. AIM: Calculate the message digest of a text using the SHA-1 algorithm in JAVA.
byte[] output = [Link]();
Secure Hash Algorithm-1: [Link]();
[Link]("SHA1(\""+input+"\") = " +bytesToHex(output));
In cryptography, SHA-1 (Secure Hash Algorithm 1) is a cryptographic hash function. SHA-1 produces a
160-bit hash value known as a message digest. The way this algorithm works is that for a message of size < 264 input = "abc";
bits it computes a 160-bit condensed output called a message digest. The SHA-1 algorithm is designed so that it [Link]([Link]());
is practically infeasible to find two input messages that hash to the same output message. A hash function such output = [Link]();
as SHA-1 is used to calculate an alphanumeric string that serves as the cryptographic representation of a file or a [Link]();
piece of data. This is called a digest and can serve as a digital signature. It is supposed to be unique and non- [Link]("SHA1(\""+input+"\") = " +bytesToHex(output));
reversible.
input = "abcdefghijklmnopqrstuvwxyz";
ALGORITHM: [Link]([Link]());
STEP-1: Read the 256-bit key values. output = [Link]();
STEP-2: Divide into five equal-sized blocks named A, B, C, D and E. [Link]();
STEP-3: The blocks B, C and D are passed to the function F. [Link]("SHA1(\"" +input+"\") = " +bytesToHex(output));
STEP-4: The resultant value is permuted with block E.
[Link]("");
STEP-5: The block A is shifted right by ‘s’ times and permuted with the result of step-4.
}
STEP-6: Then it is permuted with a weight value and then with some other key pair and taken as the first
catch (Exception e)
block.
{
STEP-7: Block A is taken as the second block and the block B is shifted by ‘s’ times and taken as the third
block. [Link]("Exception: " +e);
STEP-8: The blocks C and D are taken as the block D and E for the final output. }
}
PROGRAM:
public static String bytesToHex(byte[] b) {
import [Link].*;
char hexDigit[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
public class SHA1 {
StringBuffer buf = new StringBuffer();
public static void main(String[] a) {
for (int j=0; j<[Link]; j++)
try {
{
MessageDigest md = [Link]("SHA1");
[Link](hexDigit[(b[j] >> 4) & 0x0f]); [Link](hexDigit[b[j] & 0x0f]);
[Link]("Message digest object info: \n");
}
[Link](" Algorithm = " +[Link]());
return [Link]();
[Link](" Provider = " +[Link]());
}
[Link](" ToString = " +[Link]());
}
String input = "";
III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 40 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 41 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 42
11. AIM: Calculate the message digest of a text using the MD5 algorithm in JAVA. [Link]();
Message Digest Algorithm5 (MD5): [Link]("MD5(\""+input+"\") = " +bytesToHex(output)); OUTPUT:
MD5 processes a variable-length message into a fixed-length output of 128 bits. The input input = "abc";
message is broken up into chunks of 512-bit blocks. The message is padded so that its length is [Link]([Link]());
divisible by 512. The padding works as follows: first a single bit, 1, is appended to the end of the output = [Link]();
message. This is followed by as many zeros as are required to bring the length of the message up [Link]();
to 64 bits less than a multiple of 512. The remaining bits are filled up with 64 bits representing [Link]("MD5(\""+input+"\") = " +bytesToHex(output));
the length of the original message, modulo 264. input = "abcdefghijklmnopqrstuvwxyz";
[Link]([Link]());
The main MD5 algorithm operates on a 128-bit state, divided into four 32-bit words,
output = [Link]();
denoted A, B, C, and D. These are initialized to certain fixed constants. The main algorithm then
[Link]();
uses each 512-bit message block in turn to modify the state.
[Link]("MD5(\"" +input+"\") = " +bytesToHex(output));
ALGORITHM:
[Link]("");
STEP-1: Read the 128-bit plain text.
}
STEP-2: Divide into four blocks of 32-bits named as A, B, C and D. catch (Exception e)
STEP-3: Compute the functions f, g, h and i with operations such as, rotations, permutations, { [Link]("Exception: " +e);
etc., }
STEP-4: The output of these functions are combined together as F and performed circular }
shifting and then given to key round. public static String bytesToHex(byte[] b) {
STEP-5: Finally, right shift of ‘s’ times are performed and the results are combined together to char hexDigit[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
produce the final output. StringBuffer buf = new StringBuffer();
for (int j=0; j<[Link]; j++)
PROGRAM:
import [Link].*; {

public class MD5 { [Link](hexDigit[(b[j] >> 4) & 0x0f]);

public static void main(String[] a) { [Link](hexDigit[b[j] & 0x0f]);

try { }

MessageDigest md = [Link]("MD5"); return [Link]();

[Link]("Message digest object info: \n"); }

[Link](" Algorithm = " +[Link]()); }

[Link](" Provider = " +[Link]());


[Link](" ToString = " +[Link]());
String input = "";
[Link]([Link]());
byte[] output = [Link]();
III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 43 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 44 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 45

1(a) Aim: To find the IP address, MAC address of the machine

Theory:

IP Address:

An IP address is a unique address that identifies a device on the internet or a local network.
IP stands for Internet Protocol.

It holds information related to our location and therefore making devices available for two-
way communication.

An IP address is represented by a series of numbers segregated by periods(.). They are


expressed in the form of four pairs – an example address might be [Link] wherein
each set can range from 0 to 255.

Cycle-2 MAC Address:

MAC address is a physical address, which uniquely identifies each device on a given
network. To make communication between two networked devices, we need two addresses:

Network Security IP address and MAC address.

It stands for Media Access Control and also known as physical address, hardware address,
or BIA (Burned In Address).

It is globally unique; It means two devices cannot have the same MAC address. It is
represented in a hexadecimal format on each device, such as [Link].

It is 12-digit, and 48 bits long, out of which the first 24 bits are used for OUI (Organization
Unique Identifier), and 24 bits are for NIC/vendor specific.

Activity:

Steps:

1) Open the command prompt.


2) Enter the command “ipconfig/all” in the command prompt.
3) The MAC address and IP address are listed under the appropriate adapter as
physical address and IPv4 Address.

III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 46
Output: 1 (b) Aim: To find the neighboring machines in our network.

Theory:

Neighbouring Machines:

In computer networks, neighbouring machines refer to the devices or computers that are
directly connected to each other, either physically or logically. These machines are usually
located in the same network segment or subnet and can communicate with each other using
various protocols and technologies.

They are important in computer networks because they are responsible for forwarding data
packets to their destination.

Examples of neighbouring machines include routers, switches, hubs and other network
devices. These are typically connected using ethernet cables or wireless connections.

Activity:

Steps:

1) Open the command prompt.


2) Enter the command arp -a in the command prompt.
3) We can see the list of all devices connected to our network, including
neighbouring machines in the output.

Output:

III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 47 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 48 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 49

1 (c) Aim: To check if a server is up and running. 2. Aim: To run tcpdump/ windump utility with atleast 4 options.  icmp: Captures ICMP packets.

Theory: Theory:
Installing tcpdump tool in Linux
Server: A server is a computer program or device that provides functionality to other “tcpdump” command:
programs or devices, known as clients, on a network. Servers can provide a wide range of apt install tcpdump
“tcpdump” is a command-line tool used for capturing and analyzing network traffic on
services such as file storage, data backup, email, web hosting and database management.
Unix/Linux systems. On Windows, a similar tool is available called “WinDump”
To capture the packets of current network interface
Servers can be physically located within an organization’s infrastructure, or they can be
The syntax for the command is as follows:
hosted remotely by a third-party provider. sudo tcpdump
tcpdump [options] [expression]
When a server is functioning properly and is available for use, then the server is said to be
up and running. This typically means that the server is powered on, has all necessary services “windump” command:

and applications running, and is connected to the network. windump is a packet capture and analysis tool for Windows operating systems.

A server that is not up and running may be offline, experiencing technical difficulties, or WinDump is a Windows port of tcpdump, and it offers the same capabilities as
undergoing maintenance. tcpdump but with a Windows-friendly interface. It can be downloaded and installed from the

Activity: official website of the WinPcap project, which is the library on which WinDump relies.

Steps: Once WinDump is installed, you can use it from the command prompt to capture network
traffic and save it to a file for later analysis. The syntax for the command is as follows:
1) Open the command prompt.
2) Enter the command ping <server IP address> in the command prompt. windump [options] [expression]

3) If the server is up and running, we can see responses from the server. Here are some commonly used options: To display all available interfaces

Output:  -i : Specifies the n/w interface to capture packets from


 -n : Displays IP addresses instead of hostnames
 -s : Specifies the snapshot length of each packet (in bytes)
 -c : Specifies the number of packets to capture.
 -v : Increases the verbosity of the output.
 -w : Writes the captured packets to a file instead of displaying them on the
screen

And here are some commonly used expressions:

 host <ipaddress>: captures packets sent to or from the specified IP address.


 port <number>: Captures packets on the specified port number.
 tcp: Captures TCP packets.
 udp: Captures UDP packets.

III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 50 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 51 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 52
3. Aim: To capture the packets in the system using Wireshark and to analyze any one TCP 4) Once you have captured some packets, you can analyze them by selecting any
packet in detail. packet and looking at its details.
To capture packets from a specific network interface
Theory:

Packet Capture: When data is sent over the network, it is broken down into smaller units
called packets. Packet capture involves intercepting and analyzing these packets as they
traverse the network. Capturing packets is done for trouble shooting purpose, to identify
network issues.

Wireshark: Wireshark is a popular open-source packet capture and analysis tool. It allows
users to capture, view, and analyze network traffic in real-time. Wireshark can decode a
large number of protocols.

Activity:
To capture specific number of packets
Steps:
sudo tcpdump -c 4 -i wlo1
1) Download and install Wireshark.
2) After installing Wireshark, start it and select the network interface you want to
capture packets from.

5) For example, we can analyze a TCP packet in detail by filtering for TCP
To print captured packets in ASCII format
packets.
sudo tcpdump -A -i wlo1 6) In the filter bar, type “tcp” to filter for only TCP packets.
7) Select any TCP packet from the list of captured packets. You can click on
packet to expand it and see it details.

3) Start to begin capturing packets.

III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 53 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 54 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 55

4. Aim: To detect intrusion packets using snort 4) Start Snort: Once it is installed and configured, you can start it to begin
monitoring network traffic.
Theory:
5) Analyze alerts: Snort will generate alerts when it detects intrusion packets based
Intrusion packets: on the rules you have configured. You can analyze these alerts to determine

Intrusion packets refer to network traffic that contains malicious or suspicious content that whether an intrusion has occurred.

could indicate an attempt to compromise the security of a network or system. Using Snort in Linux OS:

Intrusion packets can take many forms such as network scans, port scans, denial-of-service
1. Starting Snort in packet capture mode:
(DoS) attacks, malware downloads, or data exfiltration attempts.
sudo snort -i eth0 -c /etc/snort/[Link]
They can be detected using various security tools and technologies, such as network This command starts Snort on interface eth0 and uses the configuration file at
intrusion detection systems (NIDS), intrusion prevention systems (IPS), firewalls, or security /etc/snort/[Link].
information and event management (SIEM) systems. 2. Viewing Snort alerts in real-time:

Snort: sudo snort -i eth0 -c /etc/snort/[Link] -A console


This command starts Snort on interface eth0, uses the configuration file at
Snort is an open-source network intrusion detection and prevention system. The Snort command-
8) You can analyze various aspects of the TCP packets including: /etc/snort/[Link], and displays alerts on the console in real-time.
line interface provides a wide range of options for configuring and using the software. Snort works
 Source and Destination IP addresses 3. Reading a PCAP file with Snort:
by analyzing network traffic in real-time and looking for patterns that match specific rules or
 Source and destination ports sudo snort -r /path/to/pcap/[Link]
signatures.
 Sequence and acknowledgement numbers: These are used to keep track This command reads a PCAP file and runs it through Snort for analysis.
of the data being sent and received in the TCP connection. These rules define the characteristics of network traffic that indicate a possible security 4. Testing Snort rules:

 Flags: These indicate the type of TCP packet, such as whether it is a threat or intrusion attempt. sudo snort -T -c /etc/snort/[Link]

SYN, ACK, or FIN packet. This command tests the configuration file at /etc/snort/[Link] for syntax errors and rule
When snort detects network traffic that matches a rule, it generates an alert or takes other
 Payload: It is the actual data being sent over the TCP connection. actions, such as blocking the traffic or logging the event. conflicts.

Activity:
Steps to install and Using Snort on Windows :
Steps: 1. Download Snort from the [Link] website. ([Link]
This will install snort in the “C:\Snort” folder. It is important to have Npcap installed prior.
1) Download and install Snort.
2. Download Rules from the website. Extract the Rules file.
2) Create a Snort rule: A Snort rule is a set of instructions that tells Snort what to
3. Copy all files from the “rules” folder of the extracted folder. Now paste the rules into
look for in network traffic. You can create own custom rule or use one of the
“C:\Snort\rules” folder.
pre-defined rules provided by Snort.
6. Copy “[Link]” file from the “etc” folder of the extracted folder. You must paste it into
3) Configure Snort: You need to configure Snort to read network traffic from the “C:\Snort\etc” folder. Overwrite any existing file.
network interface you want to monitor. You also need to determine which rules 7. Open a command prompt ([Link]) and navigate to folder “C:\Snort\bin” folder. ( at the
to use for detecting intrusion packets. Prompt, type cd\snort\bin)
8. To start (execute) snort in sniffer mode use following command:
snort -dev -i 5
III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 56 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 57 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 58
-dev is used to run snort to capture packets on your network. [Link]: To demonstrate ARP poisoning. Static entries are added manually and are deleted when the computer is restarted, and the
network interface card restarted or other activities that affect it.
-i indicates the interface number. You must pick the correct interface number. Theory:

To check the interface list, use following command: ARP poisoning: dynamic entries are added and deleted automatically when using TCP/IP sessions with

snort -W remote computers.


ARP (Address Resolution Protocol) poisoning is a type of cyber-attack that involves
manipulating the ARP cache of a network in order to redirect the flow of network traffic. Adding Static Entries:

The ARP protocol is used to map an IP address to a physical MAC address on a local use the ipconfig /all command to get the IP and MAC address
network. By sending false ARP messages to a network device, an attacker can associate their
own MAC address with the IP address of another device on the network.

Once the ARP cache has been poisoned, the attacker can intercept and monitor network
traffic, steal sensitive information such as passwords, or launch further attacks such as Man-
in-the-Middle (MitM) attack.

To start snort in IDS mode ARP poisoning is sending fake MAC addresses to the switch so that it can associate the fake

snort -c c:\snort\etc\[Link] -l c:\snort\log -i 5 MAC addresses with the IP address of a genuine computer on a network and hijack the traffic.

ARP poisoning is also known as ARP spoofing or ARP cache poisoning. The MAC address is represented using the Physical Address and the IP address is
IPv4Address

Activity: Configure ARP entries in Windows Enter the following command


Steps: Run Command Prompt as Administrator, enter the following command
arp -s [Link] 54-8C-A0-52-0A-6B
arp –a
Use the following command to view the ARP cache
 arp calls the ARP configure program located in Windows/System32 directory arp –a
 -a is the parameter to display to contents of the ARP cache

The IP address has been resolved to the MAC address we provided and it is of a static type.
ARP poisoning works by sending fake MAC addresses to the switch.

III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 59 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 60 III/IV IT – II SEM, Dept. of IT & CA, AUCE Cryptography & Network Security Lab 61

You might also like