0% found this document useful (0 votes)
30 views75 pages

Ccs 354 Network Security Manual - PDF Edited2

The document outlines the implementation of various symmetric key algorithms in Java, including Caesar Cipher, Playfair Cipher, Hill Cipher, Vigenere Cipher, and Rail Fence Cipher. Each section provides an aim, algorithm, program code, and output results demonstrating successful encryption and decryption processes. The document serves as a practical guide for implementing these cryptographic techniques.
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)
30 views75 pages

Ccs 354 Network Security Manual - PDF Edited2

The document outlines the implementation of various symmetric key algorithms in Java, including Caesar Cipher, Playfair Cipher, Hill Cipher, Vigenere Cipher, and Rail Fence Cipher. Each section provides an aim, algorithm, program code, and output results demonstrating successful encryption and decryption processes. The document serves as a practical guide for implementing these cryptographic techniques.
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
You are on page 1/ 75

1.

IMPLEMENT SYMMETRIC KEY ALGORITHMS

Ex. No. 1A PERFORM ENCRYPTION, DECRYPTION USING CAESAR CIPHER

AIM:
To implement a Caesar cipher substitution technique in Java.

ALGORITHM:

1. Assign the 26 letters in alphabet to the variable named ALPHABET.


2. Convert the plaintext letters into lowercase.
3. To encrypt a plaintext letter, the first set of plaintext letters and slides it to LEFT by
the number of positions of the secret shift.
4.
The plaintext letter is then encrypted to the ciphertext letter on the sliding ruler
5. underneath.
On receiving the ciphertext, the receiver who also knows the secret shift, positions his
sliding ruler underneaththe ciphertext alphabet and slides it to RIGHT by the agreed
shiftnumber, 3 in this case.
6. Then replaces the ciphertext letter by the plaintext letter on the sliding ruler underneath.

PROGRAM:

class caesarCipher
{
public static String encode(String enc, int offset)
{ offset = offset % 26 + 26;
StringBuilder encoded = new StringBuilder(); for (char i : enc.toCharArray()) {
if (Character.isLetter(i)) {
if (Character.isUpperCase(i)) {
encoded.append((char) ('A' + (i - 'A' + offset) % 26));
} else {
encoded.append((char) ('a' + (i - 'a' + offset) % 26));
}
} else {
encoded.append(i);
}
}
return encoded.toString();
}
public static String decode(String enc, int offset)
{ return encode(enc, 26 - offset);
}

1
public static void main(String[] args) throws java.lang.Exception { String
msg =
"OXFORD COLLEGE OF ENGINEERING";
System.out.println("Simulating Caesar Cipher\n ");
System.out.println("Input : " + msg); System.out.printf("Encrypted Message : ");
System.out.println(caesarCipher.encode(msg, 3)); System.out.printf("Decrypted Message : ");
System.out.println(caesarCipher.decode(caesarCipher.encode(msg, 3), 3));
}
}
CAESARCIPHER OUTPUT:

C:\Users\abacussys1\Desktop>javac caesarCipher.java

C:\Users\abacussys1\Desktop>java caesarCipher
Simulating Caesar Cipher
Input : OXFORD COLLEGE OF ENGINEERING AND TECHNOLOGY
Encrypted Message : MM FROOHJH RI HQJLQHHULQJ DQG WHFKQRORJB
Decrypted Message : OXFORD COLLEGE OF ENGINEERING

RESULT:

Thus the Caesar cipher substitution technique was implemented and executed successfully.

2
Ex. No. 1B PERFORM ENCRYPTION, DECRYPTION USING PLAYFAIR CIPHER

AIM:
To implement a Playfair cipher substitution technique in Java.

ALGORITHM:

1. Read the keyword.


2. Then create the key table of 5x5 grid of alphabets.
3. Read the word to encrypt.
4. If the input word should be even and then process it.
5. Then the plaintext message is split into pairs of two letters (digraphs).
6. If boththe letters are in the same column, take the letter below each one.
7. If both letters are in the same row, take the letter to the right of each one.
8. If neither of the preceding two rules are true, form a rectangle with the two letters and
take the letters on the horizontal opposite corner of the rectangle.

PROGRAM:

import java.awt.Point;
class playfairCipher {
private static char[][] charTable;
private static Point[] positions;
private static String prepareText(String s, boolean chgJtoI)
{
s = s.toUpperCase().replaceAll("[^A-Z]", "");
return chgJtoI ? s.replace("J", "I") : s.replace("Q", "");
}
private static void createTbl(String key, boolean chgJtoI)
{ charTable = new char[5][5]; positions = new Point[26];
String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", chgJtoI);
int len = s.length();
for (int i = 0, k = 0; i < len; i++)
{
char c = s.charAt(i);
if (positions[c - 'A'] == null)
{
charTable[k / 5][k % 5] = c;
positions[c - 'A'] = new Point(k % 5, k / 5); k++;
}
}
}
private static String codec(StringBuilder txt, int dir)
{ int len = txt.length();

3
for (int i = 0; i < len; i += 2) { char a = txt.charAt(i);
char b = txt.charAt(i + 1);
int row1 = positions[a - 'A'].y; int row2 = positions[b - 'A'].y;
int col1 = positions[a - 'A'].x;
int col2 = positions[b - 'A'].x;
if (row1 == row2) {
col1 = (col1 + dir) % 5; col2 = (col2 + dir) % 5;
}
else if (col1 == col2) {
row1 = (row1 + dir) % 5; row2 = (row2 + dir) % 5;
} else
{
int tmp = col1; col1 = col2; col2 = tmp; }
txt.setCharAt(i, charTable[row1][col1]);
txt.setCharAt(i + 1, charTable[row2]
[col2]); } return txt.toString(); } private
static String encode(String s) {
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length(); i += 2) { if (i
== sb.length() - 1) { sb.append(sb.length()
% 2 == 1 ? 'X' : "");
}
else if (sb.charAt(i) == sb.charAt(i + 1))
{ sb.insert(i + 1, 'X');
}
}
return codec(sb, 1);
}
private static String decode(String s) {

return codec(new StringBuilder(s), 4);


}
public static void main(String[] args) throws java.lang.Exception {
String key = "CSE";
String txt = "OXFORD COLLEGE OF ENGINEERING ";
/* make sure string length is even */ /* change J to I */ boolean chgJtoI = true;
createTbl(key, chgJtoI);
String enc = encode(prepareText(txt, chgJtoI));
System.out.println("Simulating Playfair Cipher\n -------------------- ");
System.out.println("Input Message : " + txt);
System.out.println("Encrypted Message : " + enc);
System.out.println("Decrypted Message : " + decode(enc));
}
}

4
PLAYFAIR CIPHER OUTPUT C:\Users\abacussys1\Desktop>javac

playfairCipher.java C:\Users\abacussys1\Desktop>java playfairCipher Simulating

Playfair Cipher

Input Message : OXFORD COLLEGE OF ENGINEERING


Encrypted Message : GZDBKMMSMGLIAMHDMAGXHOHEKHRAADOKMKHX
Decrypted Message : IXICOLLEGEOFENGINEERINGANDTECHNOLOGY

RESULT:

Thus the Play fair cipher substitution technique was implemented and executed successfully.

5
Ex. No. 1C PERFORM ENCRYPTION, DECRYPTION USING HILL CIPHER

AIM:
To implement a Hill cipher substitution technique in Java.

ALGORITHM:

1. Obtain a plaintext message to encode in standard English with no spaces.


2.Split the plaintext into group of length three. To fill this, add X at the end.
3.Convert each group of letters with length three into plaintext vectors.
4. Replace each letter by the number corresponding to its position in the alphabet i.e.A=1, B=2,
C=3…Z=0.
5. Create the keyword in a 3*3 matrix.
6. Multiply the two matrices to obtain the cipher text of length three.
7. For decryption, convert each entry in the ciphertext vector into its plaintext vector by
multiplying the cipher text vector and inverse of a matrix.
8. Thus plain text is obtained fromcorresponding plaintext vector by correspondingposition
in the alphabet.

PROGRAM:

class hillCipher
{
public static int[][] keymat = new int[][] { { 1, 2, 1 }, { 2, 3, 2 },
{ 2, 2, 1 } };
public static int[][] invkeymat = new int[][] { { -1, 0, 1 }, { 2, -1, 0 }, { -2, 2, -1 } };
public static String key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static String encode(char a, char b, char c)
{ String ret = "";
int x, y, z;
int posa = (int) a - 65;
int posb = (int) b - 65;
int posc = (int) c - 65;
x = posa * keymat[0][0] + posb * keymat[1][0] + posc * keymat[2][0];
y = posa * keymat[0][1] + posb * keymat[1][1] + posc * keymat[2][1];
z = posa * keymat[0][2] + posb * keymat[1][2] + posc * keymat[2][2];
a = key.charAt(x % 26);
b = key.charAt(y % 26);
c = key.charAt(z % 26);
ret = "" + a + b + c;
return ret;
}

6
private static String decode(char a, char b, char c) {
String ret = ""; int x, y, z; int posa = (int) a - 65; int
posb = (int) b - 65; int posc = (int) c - 65;
x=posa*invkeymat[0][0]+posb*invkeymat[1]
[0]+posc

* invkeymat[2][0];
y = posa * invkeymat[0][1] + posb * invkeymat[1][1] + posc* invkeymat[2][1];
z = posa * invkeymat[0][2] + posb * invkeymat[1][2] + posc * invkeymat[2]
[2]; a = key.charAt((x % 26 < 0) ? (26 + x % 26) : (x % 26)); b =
key.charAt((y % 26 < 0) ? (26 + y % 26) : (y % 26)); c = key.charAt((z % 26 <
0) ? (26 + z % 26) : (z % 26)); ret = "" + a + b + c; return ret; } public static
void main(String[] args) throws java.lang.Exception { String msg; String enc
= ""; String dec = ""; int n; msg = ("OXFORD COLLEGE OF
ENGINEERING AND TECHNOLOGY ");

System.out.println("simulation of Hill Cipher\n ");


System.out.println("Input message : " + msg); msg = msg.toUpperCase(); msg = msg.replaceAll("\\s", "");
n = msg.length() % 3;
if (n != 0) {
for (int i = 1; i <= (3 - n); i++) {
msg += 'X'; } }
System.out.println("padded message : " + msg);
char[] pdchars = msg.toCharArray();
for (int i = 0; i < msg.length(); i += 3) {
enc += encode(pdchars[i], pdchars[i + 1], pdchars[i + 2]);
} System.out.println("encoded message : " + enc);
char[] dechars = enc.toCharArray();
for (int i = 0; i < enc.length(); i += 3) { dec += decode(dechars[i], dechars[i + 1], dechars[i +
2]); }System.out.println("decoded message : " + dec); } }
HILL CIPHER OUTPUT:

C:\Users\abacussys1\Desktop>javac hillCipher.java
C:\Users\abacussys1\Desktop>java hillCipher
simulation of Hill Cipher
Input message : OXFORD COLLEGE OF ENGINEERING AND TECHNOLOGY
padded message : OXFORDCOLLEGEOFENGINEERINGANDTECHNOLOGYX
encoded message : FXDGFVYIUGZCPIHDUZHGUGMTXTTQZDMLYWAZ
decoded message : OXFORDCOLLEGEOFENGINEERINGANDTECHNOLOGYX

RESULT:
Thus the Hill cipher substitution technique was implemented and executed successfully.

7
Ex. No. 1D PERFORM ENCRYPTION, DECRYPTION USING VIGENERE CIPHER

AIM:
To implement a Java program for encryption and decryption using Vigenere cipher
substitution technique.
ALGORITHM:

1. The Vigenere cipher is a method of encrypting alphabetic text by using a series ofdifferent
Caesar ciphers based on the letters of a keyword.
2. It is a simple form of polyalphabetic substitution.
3. To encrypt, a table of alphabets can be used, termed a Vigenere square, or Vigenere table.
4. It consists of the alphabet written out 26 times in different rows, each alphabet shiftedcyclically
5. 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 fromone of the
6. rows used.
The alphabet at each point depends on a repeating keyword.

PROGRAM:

public class vigenereCipher {


static String encode(String text, final String key)
{ String res = "";
text = text.toUpperCase();
for (int i = 0, j = 0; i < text.length(); i++) { char c = text.charAt(i);
if (c < 'A' || c > 'Z') { continue;
}
res += (char) ((c + key.charAt(j) - 2 * 'A') % 26 + 'A'); j = ++j % key.length();
}
return res;
}

static String decode(String text, final String key)


{ String res = "";
text = text.toUpperCase();
for (int i = 0, j = 0; i < text.length(); i++) {
char c = text.charAt(i); if (c < 'A' || c > 'Z') {
continue;
}
res += (char) ((c - key.charAt(j) + 26) % 26 + 'A'); j = ++j % key.length();
}
return res;
}

public static void main(String[] args) throws java.lang.Exception { String key =

"VIGENERECIPHER";
String msg = "OXFORD COLLEGE OF ENGINEERING AND TECHNOLOGY";
System.out.println("Simulating Vigenere Cipher\n");
System.out.println("Input Message : " + msg); String enc = encode(msg, key);
8
System.out.println("Encrypted Message : " + enc);
System.out.println("Decrypted Message : " + decode(enc,
key)); } }

Vigenere Cipher Output:

C:\Users\abacussys1\Desktop>javac vigenereCipher.java

C:\Users\abacussys1\Desktop>java vigenereCipher
Simulating Vigenere Cipher
Input Message : OXFORD COLLEGE OF ENGINEERING AND TECHNOLOGY
Encrypted Message : ERISYPVKGWULRXDVKIEMEKCVSAITCVUPBKP
Decrypted Message : OXFORDCOLLEGEOFENGINEERINGANDTECHNOLOGY

RESULT:
Thus the Vigenere cipher substitution technique was implemented and executed successfully

9
Ex. No. 1E PERFORM ENCRYPTION, DECRYPTION USING RAILFENCE
AIM: TECHNIQUE
To implement a program for encryption and decryption using railfence transposition technique.

ALGORITHM:

1. In the rail fence cipher, the plain text is written downwards and diagonally on successive "rails"
of an imaginary fence, then moving up when we reach the bottom rail.
2. When we reach the top rail, the message is written downwards again until the whole plaintext is
written out.
3. The message is then read off in rows.

PROGRAM
class railfenceCipherHelper {
int depth;
String encode(String msg, int depth) throws Exception
{
int r = depth;
int l = msg.length();
int c = l / depth;
int k = 0;
char mat[][] = new char[r][c]; String enc = "";
for (int i = 0; i < c; i++) { for (int j = 0; j < r; j++)
{
if (k != l) {
mat[j][i] = msg.charAt(k++);
} else {
mat[j][i] = 'X';
}
}
}
for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) {
enc += mat[i][j];
}
}
return enc;
}

String decode(String encmsg, int depth) throws Exception


{ int r = depth;
int l = encmsg.length(); int c = l / depth;
int k = 0;
char mat[][] = new char[r][c]; String dec = "";
for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) {

10
mat[i][j] = encmsg.charAt(k++); } } for (int i = 0; i < c; i++) { for (int j = 0;
j < r; j++) { dec += mat[j][i]; } } return dec; } } class railFenceCipher {
public static void main(String[] args) throws java.lang.Exception {
railfenceCipherHelper rf = new railfenceCipherHelper();
String msg, enc, dec;
msg = "OXFORD COLLEGE OF ENGINEERING AND
TECHNOLOGY,TRICHY";
int depth = 2; enc = rf.encode(msg, depth); dec = rf.decode(enc, depth);
System.out.println("Simulating Railfence Cipher\n ");
System.out.println("Input Message : " + msg);
System.out.println("Encrypted Message : " + enc);
System.out.printf("Decrypted Message : " + dec); } }

RailFenceCipher Output:

C:\Users\abacussys1\Desktop>javac railFenceCipher.java

C:\Users\abacussys1\Desktop>java railFenceCipher
Simulating Railfence Cipher
Input Message : OXFORD COLLEGE OF ENGINEERING AND

TECHNOLOGY,TRICHY
Encrypted Message : J OLG FEGNEIGADTCNLG,RCJCLEEO NIERN N EHOOYTIH
Decrypted Message : OXFORD COLLEGE OF ENGINEERING AND
TECHNOLOGY,TRICHY

RESULT:
Thus the Rail Fence Transposition Technique was implemented and executed
successfully.

11
Ex. No. 1F PERFORM ENCRYPTION, DECRYPTION USING ROW AND COLUMN
TRANSFORMATION TECHNIQUE
AIM:
To implement a program for encryption and decryption by using row and column
transformation technique.

ALGORITHM:
1. Consider the plain text hello world, and let us apply the simple columnartransposition
technique as shown below

h e l l
o w o r
l d

2. The plain text characters are placed horizontally and the cipher text is created withvertical format as:
holewdlo lr.
Now, the receiver has to use the same table to decrypt the cipher text to plain text.

PROGRAM:
import java.util.*;
class TransCipher {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the plain text");
String pl = sc.nextLine();
sc.close(); String s = "";
int start = 0;
for (int i = 0; i < pl.length(); i++) {
if (pl.charAt(i) == ' ') {
s = s + pl.substring(start, i);
start = i + 1;
}
}
s = s + pl.substring(start);
System.out.print(s);

System.out.println();
// end of space deletion
int k = s.length();
int l = 0;

12
int col = 4; int row = s.length() / col; char ch[][] = new
char[row][col]; for (int i = 0; i < row; i++) { for (int j =
0; j < col; j++) { if (l < k) { ch[i][j] = s.charAt(l); l++; }
else { ch[i][j] = '#'; } } }
// arranged in matrix
char trans[][] = new char[col][row];
for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++)
{
trans[j][i] = ch[i][j];
}
}
for (int i = 0; i < col; i++) { for (int j = 0; j < row; j++)
{
System.out.print(trans[i][j]);
}
}
// display System.out.println();
}
}

Row and Column Transformation Technique Output:

C:\Users\abacussys1\Desktop>javac TransCipher.java

C:\Users\abacussys1\Desktop>java

TransCipher
Enter the plain text
oxford college of engineering and technology
oxford collegeofengineering and technology
jlenendhjlogegtncefiraeoogenincl

RESULT:
Thus the Row and Column Transposition Technique was implemented and executed successfully.

13
EX. NO. 1G PERFORM ENCRYPTION, DECRYPTION USING DATA ENCRYPTION
STANDARD ALGORITHM

AIM:
To apply Data Encryption Standard (DES) Algorithm for a practical application like User Message
Encryption.

ALGORITHM:

1. Create a DES Key.


2. Create a Cipher instance from Cipher class, specify the following informationand separated bya

 slash (/).
 Algorithm name
3. Mode (optional)
4. Padding scheme (optional)
5. Convert String into Byte[] array format.
Make Cipher in encrypt mode, and encrypt it with Cipher.doFinal() method.
Make Cipher in decrypt mode, and decrypt it with Cipher.doFinal() method.

PROGRAM:

public class DES


{
public static void main(String[] argv) {

try{
System.out.println("Message Encryption Using DES Algorithm\n ");
KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
SecretKey myDesKey = keygenerator.generateKey();
Cipher desCipher;

desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
byte[] text = "OXFORD COLLEGE OF ENGINEERING AND TECHNOLOG ".
getBytes();
System.out.println("Message [Byte Format] : " + text);
System.out.println("Message : " + new String(text));
byte[] textEncrypted = desCipher.doFinal(text);
System.out.println("Encrypted Message: " + textEncrypted);
desCipher.init(Cipher.DECRYPT_MODE, myDesKey);
byte[] textDecrypted = desCipher.doFinal(textEncrypted);
System.out.println("Decrypted Message: " + new String(textDecrypted));
}

14
catch(NoSuchAlgorithmException e)
{ e.printStackTrace(); }
catch(NoSuchPaddingException e) {
e.printStackTrace(); }
catch(InvalidKeyException e) {
e.printStackTrace(); }
catch(IllegalBlockSizeException e){
e.printStackTrace(); }
catch(BadPaddingException e){
e.printStackTrace(); } } }

DES Output:
C:\Users\abacussys1\Desktop>javac DES.java

C:\Users\abacussys1\Desktop>java DES
Message Encryption Using DES Algorithm
Message [Byte Format] : [B@14189d0
Message : OXFORD COLLEGE OF ENGINEERING AND TECHNOLOGY
Encrypted Message: [B@1f796d0
Decrypted Message: OXFORD COLLEGE OF ENGINEERING AND TECHNOLOGY

RESULT:
Thus the java program for applying Data Encryption Standard (DES) Algorithm for apractical
application of User Message Encryption is written and executed successfully

15
Ex. No. 1H PERFORM ENCRYPTION, DECRYPTION USING ADVANCED
ENCRYPTION STANDARD (AES)

AIM: To apply Advanced Encryption Standard (AES) Algorithm for a practical application
like URL Encryption.
ALGORITHM:

1. AES is based on a design principle known as a substitution–permutation.


2. AES does not use a Feistel network like DES, it uses variant of Rijndael.
3. It has a fixed block size of 128 bits, and a keysize of 128, 192, or 256 bits.
4. AES operates on a 4 × 4 column- major order arrayof bytes, termed the state

PROGRAM:
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class AES {
private static SecretKeySpec secretKey;
private static byte[] key;
public static void setKey(String myKey) {
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException e)
{ e.printStackTrace();
} catch (UnsupportedEncodingException e)
{ e.printStackTrace(); }
}
public static String encrypt(String strToEncrypt, String secret)
{ try {
setKey(secret);
Cipher cipher
=Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);

16
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-
8"))); } catch (Exception e) { System.out.println("Error while encrypting: " + e.toString()); }
return null; }
public static String decrypt(String strToDecrypt, String secret)
{
try
{
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt))); }
catch (Exception e) {
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
public static void main(String[] args) {
final String secretKey = "annaUniversity";
String originalString = "www.annauniv.edu";
String encryptedString = AES.encrypt(originalString, secretKey);
String decryptedString = AES.decrypt(encryptedString, secretKey);
System.out.println("URL Encryption Using AES Algorithm\n ----------- ");
System.out.println("Original URL : " + originalString);
System.out.println("Encrypted URL : " + encryptedString);
System.out.println("Decrypted URL : " + decryptedString);
}
}

OUTPUT:
URL Encryption Using AES Algorithm

Original URL : www.annauniv.edu


Encrypted URL : vibpFJW6Cvs5Y+L7t4N6YWWe07+JzS1d3CU2h3mEvEg=Decrypted URL :
www.annauniv.edu

RESULT:
Thus the java program for applying Advanced Encryption Standard (AES) Algorithmfor a
practical application of URL encryption is written and executed successfully.

17
Ex. No. 1I PERFORM ENCRYPTION, DECRYPTION USING SHA-1 ALGORITHM

AIM:

To calculate the message digest of a text using the SHA-1 algorithm in Java.

ALGORITHM:

1. Append Padding bits.


2. Append Length - 64 bits are appended to the end.
3. Prepare Processing Functions.
4. Prepare Processing Constants.
5. Initialize Buffers.
6. Processing Message in 512-bit blocks (L blocks in total message).

PROGRAM
import java.security.*;
public class sha1 {
public static void main(String[] a) { try {
MessageDigest md = MessageDigest.getInstance("SHA1");
System.out.println("Message digest object info:\n ");
System.out.println("Algorithm=" + md.getAlgorithm());
System.out.println("Provider=" + md.getProvider());
System.out.println("ToString=" + md.toString());
String input = "";
md.update(input.getBytes()); byte[] output = md.digest();
System.out.println();
System.out.println("SHA1(\"" + input + "\")=" + bytesToHex(output));
input = "abc";
md.update(input.getBytes()); output = md.digest();
System.out.println();
System.out.println("SHA1(\"" + input + "\")=" + bytesToHex(output));
input = "abcdefghijklmnopqrstuvwxyz"; md.update(input.getBytes());

output = md.digest();
System.out.println();
System.out.println("SHA1(\"" + input + "\")=" + bytesToHex(output));
System.out.println();
} catch (Exception e) {
System.out.println("Exception:" + e);
}
}

18
private static String bytesToHex(byte[] b) { char hexDigit[] = { '0', '1', '2',
'3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; StringBuffer buf = new
StringBuffer(); for (byte aB : b) { buf.append(hexDigit[(aB >> 4) & 0x0f]);
buf.append(hexDigit[aB & 0x0f]); } return buf.toString(); } }

SHA1 output:

C:\Users\abacussys1\Desktop>javac sha1.java

C:\Users\abacussys1\Desktop>java sha1
Message digest object info:
Algorithm=SHA1
Provider=SUN version 1.7
ToString=SHA1 Message Digest from SUN, <initialized>

SHA1("")=DA39A3EE5E6B4B0D3255BFEF95601890AFD80709

SHA1("abc")=A9993E364706816ABA3E25717850C26C9CD0D89D

SHA1("abcdefghijklmnopqrstuvwxyz")=32D10C7B8CF96570CA04CE37F2A19D84240D3A89

RESULT

Thus the Secure Hash Algorithm (SHA-1) has been implemented and executed successfully.

19
2 IMPLEMENT ASYMMETRIC KEY ALGORITHMS AND KEY EXCHANGE
ALGORITHMS

EX. NO. 2A RSA ALGORITHM

AIM:
To implement RSA(Rivest–Shamir–Adleman) algorithm by using HTML and Javascript.

ALGORITHM:

1. Choose two prime number p and q


2. Compute the value of n and p
3. Find the value of e(publickey)
4. Compute the value of d(private key) using gcd()
5. Do the encryption and decryption
Encryption is given as,
6. e
c=t mod n
7. Decryption is given as,
d
t=c modn

PROGRAM:

<html>
<head>
<title>RSA Encryption</title>
<meta name="viewport" content="width=device-width, initial- scale=1.0"> </head>
<body>
<center>
<h1>RSA Algorithm</h1>
<h2>Implemented Using HTML & Javascript</h2>
<hr>
<table>
<tr>
<td>Enter First Prime Number:</td>
<td><input type="number" value="53" id="p"></td>
</tr>
<tr>
<td>Enter Second Prime Number:</td>
<td><input type="number" value="59" id="q"></p> </td>
</tr>
<tr>

20
<td>Enter the Message(cipher text):<br>[A=1, B=2,...]</td> <td><input type="number"
value="89" id="msg"></p> </td>
</tr>
<tr>
<td>Public Key:</td>
<td>
<p id="publickey"></p>
</td>
</tr>
<tr>
<td>Exponent:</td>
<td>
<p id="exponent"></p>
</td>
</tr>
<tr>
<td>Private Key:</td>
<td>
<p id="privatekey"></p>
</td>
</tr>
<tr>
<td>Cipher Text:</td>
<td>
<p id="ciphertext"></p>
</td>
</tr>
<tr>
<td><button onclick="RSA();">Apply RSA</button></td> </tr>
</table>
</center>
</body>
<script type="text/javascript"> function RSA() {
var gcd, p, q, no, n, t, e, i, x;
gcd = function (a, b) { return (!b) ? a : gcd(b, a % b);
}; p = document.getElementById('p').value; q = document.getElementById('q').value;
no = document.getElementById('msg').value; n = p * q;
t = (p - 1) * (q - 1);
for (e = 2; e < t; e++) { if (gcd(e, t) == 1) {
break;
}
}
for (i = 0; i < 10; i++) { x = 1 + i * t
if (x % e == 0) { d = x / e; break;
}
}

21
ctt = Math.pow(no, e).toFixed(0); ct = ctt % n; dtt = Math.pow(ct, d).toFixed(0); dt = dtt %
n; document.getElementById('publickey').innerHTML = n;
document.getElementById('exponent') .innerHTML = e;
document.getElementById('privatekey').innerHTML = d;
document.getElementById('ciphertext').innerHTML = ct;
}
</script>
</html>

RSA OUTPUT:

RESULT:

Thus the RSA algorithm was implemented using HTML and Javascript
and executed successfully

22
EX. NO. 2B DIFFIE-HELLMAN KEY EXCHANGE ALGORITHM

AIM:
To implement the Diffie-Hellman Key Exchange algorithm for a given problem.

ALGORITHM:

1. Sender and receiver publicly agree to use a modulus p and base g which is a primitiveroot
modulo p.
2. Sender chooses a secret integer x then sends Bob R1 = gx mod p
3. Receiver chooses a secret integer y, then sends Alice R2 = gy mod p
4. Sender computes k1 = Bx mod p
5. Receiver computes k2 = Ay mod p
6. Sender and Receiver now share a secret key.

PROGRAM:

class DiffieHellman
{
public static void main(String args[])
{
int p = 23; /* publicly known (prime number)
*/ int g = 5; /* publicly known (primitive root)
*/ int x = 4; /* only Alice knows this secret */ int y = 3; /* only Bob knows this secret */ double
aliceSends = (Math.pow(g, x)) % p;
double bobComputes = (Math.pow(aliceSends, y)) % p; double bobSends =
(Math.pow(g, y)) % p;
double aliceComputes = (Math.pow(bobSends, x)) % p; double sharedSecret =
(Math.pow(g, (x * y))) % p;
System.out.println("simulation of Diffie-Hellman key exchange algorithm\n -----------");
System.out.println("Alice Sends : " + aliceSends);
System.out.println("Bob Computes : " + bobComputes);
System.out.println("Bob Sends : " + bobSends); System.out.println("Alice Computes :
" + aliceComputes);
System.out.println("Shared Secret : " + sharedSecret);
/* shared secrets should match and equality is transitive */
if ((aliceComputes == sharedSecret) && (aliceComputes == bobComputes))
System.out.println("Success: Shared Secrets Matches! " + sharedSecret);
else
System.out.println("Error: Shared Secrets does not Match");
}
}

23
DiffieHellman output:

C:\Users\abacussys1\Desktop>javac DiffieHellman.java

C:\Users\abacussys1\Desktop>java DiffieHellman
simulation of Diffie-Hellman key exchange algorithm
Alice Sends : 4.0
Bob Computes : 18.0
Bob Sends : 10.0
Alice Computes : 18.0
Shared Secret : 18.0
Success: Shared Secrets Matches! 18.0

RESULT:
Thus the Diffie-Hellman key exchange algorithm was implemented and executed successfully.

24
EX. NO. 3 IMPLEMENT DIGITAL SIGNATURE SCHEMES

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

ALGORITHM:

1. Declare the class and required variables.


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

PROGRAM:

import java.util.*;
import java.math.BigInteger; class
dsaAlg {
final static BigInteger one = new BigInteger("1"); final
static BigInteger zero = new BigInteger("0"); public
static BigInteger getNextPrime(String ans)
{
BigInteger test = new BigInteger(ans);while
(!test.isProbablePrime(99))
e:
{
test = test.add(one);
}
return test;
}
public static BigInteger findQ(BigInteger n)
{
BigInteger start = new BigInteger("2");while
(!n.isProbablePrime(99))
{
while (!((n.mod(start)).equals(zero)))
{
start = start.add(one);
}

25
n = n.divide(start);
}
return n;
}
public static BigInteger getGen(BigInteger p, BigInteger q,Random r)
{
BigInteger h = new BigInteger(p.bitLength(), r);h =
h.mod(p);
return h.modPow((p.subtract(one)).divide(q), p);
}
public static void main (String[] args) throwsjava.lang.Exception
{
Random randObj = new Random();
BigInteger p = getNextPrime("10600"); /* approximateprime */
BigInteger q = findQ(p.subtract(one));
BigInteger g = getGen(p,q,randObj);
System.out.println(" \n simulation of Digital Signature Algorithm \n");
System.out.println(" \n global public key components are:\n");
System.out.println("\np is: " + p);
System.out.println("\nq is: " + q);
System.out.println("\ng is: " + g);
BigInteger x = new BigInteger(q.bitLength(), randObj);x =
x.mod(q);
BigInteger y= g.modPow(x,p);
BigInteger k = new BigInteger(q.bitLength(), randObj);k =
k.mod(q);
BigInteger r = (g.modPow(k,p)).mod(q);
BigInteger hashVal = new BigInteger(p.bitLength(),randObj);
BigInteger kInv = k.modInverse(q);
BigInteger s = kInv.multiply(hashVal.add(x.multiply(r)));s =
s.mod(q);
System.out.println("\nsecret information are:\n");
System.out.println("x (private) is:" + x);
System.out.println("k (secret) is: " + k);
System.out.println("y (public) is: " + y);
System.out.println("h (rndhash) is: " + hashVal);
System.out.println("\n generating digital signature:\n");
System.out.println("r is : " + r);
System.out.println("s is : " + s);
BigInteger w = s.modInverse(q);
BigInteger u1 = (hashVal.multiply(w)).mod(q);
BigInteger u2 = (r.multiply(w)).mod(q);
BigInteger v = (g.modPow(u1,p)).multiply(y.modPow(u2,p));v =
(v.mod(p)).mod(q);

26
System.out.println("\nverifying digital signature (checkpoints)\n:");
System.out.println("w is : " + w);
System.out.println("u1 is : " + u1);
System.out.println("u2 is : " + u2);
System.out.println("v is : " + v);
if (v.equals(r))
{
System.out.println("\nsuccess: digital signature is verified!\n " + r);
}
else
{
System.out.println("\n error: incorrect digital signature\n ");
}
}
}

OUTPUT:

C:\Security Lab New\programs>javac dsaAlg.java


C:\Security Lab New\programs>java dsaAlg
simulation of Digital Signature Algorithm
global public keycomponents are:
p is: 10601
q is: 53
g is: 6089
secret information are:
x (private) is:6k (secret)
is: 3
y (public) is: 1356
h (rndhash) is: 12619 generating
digital signature:
r is : 2s is :41
verifying digital signature (checkpoints):
w is : 22 u1 is : 4
u2 is : 44v is
:2
success: digital signature is verified!2

RESULT:

Thus the Digital Signature Standard Signature Scheme has been implemented andexecuted
successfully.

27
EX. NO. 4. INSTALLATION OF WIRE SHARK, TCP DUMP
AIM:
To Install Wire shark, tcpdump and observe data transferred in client-server communication using
UDP/TCP and identify the UDP/TCP datagram.

PROCEDURE:

Wireshark is a free open- source network protocol analyzer. It is used for network troubleshooting
and communication protocol analysis. Wireshark captures network packets in real time and display
them in human-readable format. It provides many advanced features including live capture and
offline analysis, three-pane packet browser, coloring rules for analysis. This document uses
Wireshark for the experiments, and it covers Wireshark installation, packet capturing, and protocol
analysis.

After you select the interface, you can click start to capture the packets as shown in the figure
Test Run

32
Do the following steps:

1. Start up the Wireshark program (select an interface and press start to capture packets).
2. Start up your favorite browser (ceweasel in Kali Linux).
3. In your browser, go to Wayne State homepage by typing www.wayne.edu.
4. After your browser has displayed the http://www.wayne.edu page, stop Wireshark packet
capture by selecting stop in the Wireshark capture window. This will cause the Wireshark
capture window to disappear and the main Wireshark window to display all packets
captured since you began packet capture see image below:

Color Coding: You’ll probably see packets highlighted in green, blue, and black.
Wireshark uses colors to help you identify the types of traffic at a glance. By default,
green is TCP traffic, dark blue is DNS traffic, light blue is UDP traffic, and black
identifies TCP packets with problems — for example, they could have been delivered out-
of-order.
You now have live packet data that contains all protocol messages exchanged between

your computer and other network entities! However, as you will notice the HTTP
messages are not clearly shown because there are many other packets included in the
packet capture. Even though the only action you took was to open your browser, there are
many other programs in your computer that communicate via the network in the
background. To filter the connections to the ones we want to focus on, we have to use the
filtering functionality of Wireshark by typing “http” in the filtering field as shown below:
Notice that we now view only the packets that are of protocol HTTP. However, we also
still do not have the exact communication we want to focus on because using HTTP as a
filter is not
connection to descriptive enough to allow us to find our
http://www.wayne.edu. We need to be more precise if we want to capture the correct set
of packets.
To further filter packets in Wireshark, we need to use a more precise filter. By setting the
http.host www.wayne.edu, we are restricting the view to packets that have as an http host
the www.wayne.edu website. Notice that we need two equal signs to perform the match

not just one. See the screenshot below

33
Now, we can try another protocol. Let’s use Domain Name System (DNS) protocol as an
example here.

Let us try now to find the conversations (also called network flows), select one of
the packets and press the right mouse button (if you are on a Mac use the
command button and click), you should see something similar to the screen below:

Click on Follow UDP Stream, and then you will see following screen.

34
If we close this window and change the filter back to “http.hos ww.wayne.edu” and then follow a
packetfrom the list of packets that match that filter, we should get the something similar to the
followingscreens.
Note that we click on Follow TCP Stream this time.

RESULT:
Installation of Wire shark, tcpdump and observe data transferred in client-server communication
usingUDP/TCP and identify the UDP/TCP datagram.

35
EX. NO. 5 CHECK MESSAGE INTEGRITY AND CONFIDENTIALITY USING SSL

Aim:
To check message integrity and confidentiality using SSL.

PROCEDURE:

Handshaking - Ciphersuit Negotiation


Client sends a plaintext Client_Hello message and suggests some cryptographic parameters (collectively
called ciphersuit) to be used for their communication session. The Client_Hellomessage also contains a 32-
byte random number denoted as client_random. For example,
Client_Hello:
Protocol Version: TLSv1 if you can, else SSLv3. Key Exchange: RSA if you can, else Diffe-Hellman.
Secret Key Cipher Method: 3DES if you can, else DES.Message Digest: SHA-1 if you can, else MD5.
Data Compression Method: PKZip if you can, else gzip.Client Random Number: 32 bytes.
The stronger method (in terms of security) shall precede the weaker one, e.g. RSA (1024-bit) precedes DH,
3DES precedes DES, SHA-1 (160-bit) precedes MD5 (128-bit).
Server responds with a plaintext Server_Helllo to state the ciphersuit of choice (server decides on the
ciphersuit). The message also contains a 32-byte random number denoted as server_random. For
example,

Server_Hello:
Protocol Version: TLSv1.
Key Exchange: RSA.
Secret Key Cipher Method: DES.Message Digest: SHA-1.
Data Compression Method: PKZip.Server Random Number: 32 bytes.
Handshaking - Key Exchange
The server sends its digital certificate to the client, which is supposedly signed by a root CA. The client
uses the root CA's public key to verify the server's certificate (trusted root-CAs' public key are pre-
installed inside the browser). It then retrieves the server's public key from the server's certificate. (If the
server's certificate is signed by a sub-CA, the client has to build a digital certificate chain, leading to a
trusted root CA, to verify the server's certificate.)

The server can optionally request for the client's certificate to authenticate the client. In practice,server
usually does not authenticate the client. This is because:
A SSL Session Trace

We could use OpenSSL's s_client (with debug option) to produce a SSL session trace.

> openssl s_client ?


(Display the available options)

36
The following command turns on the debug option and forces the protocol to be TLSv1:
> openssl s_client -connect localhost:443 -CAfile ca.crt -debug -tls1

Loading 'screen' into random state - doneCONNECTED(00000760)

write to 00988EB0 [009952C8] (102 bytes => 102 (0x66))


0000 - 16 03 01 00 61 01 00 00-5d 03 01 40 44 35 27 5c ....a...]..@D5'\
0010 - 5a e8 74 26 e9 49 37 e2-06 3b 1c 6d 77 37 d1 ae Z.t&.I7..;.mw7..
0020 - 44 07 86 47 98 fa 84 1a-8d f4 72 00 00 36 00 39 D..G .................... r..6.9
0030 - 00 38 00 35 00 16 00 13-00 0a 00 33 00 32 00 2f .8.5.......3.2./
0040 - 00 07 00 66 00 05 00 04-00 63 00 62 00 61 00 15 ...f.....c.b.a..
0050 - 00 12 00 09 00 65 00 64-00 60 00 14 00 11 00 08 .....e.d.`......
0060 - 00 06 00 03 01 .....
0066 - <SPACES/NULS>
read from 00988EB0 [00990AB8] (5 bytes => 5 (0x5))0000 - 16 03 01 00 2a *
read from 00988EB0 [00990ABD] (42 bytes => 42 (0x2A))
0000 - 02 00 00 26 03 01 40 44-35 27 cc ef 2b 51 e1 b0 ...&..@D5'..+Q..
0010 - 44 1f ef c4 83 72 df 37-4f 9b 2b dd 11 50 13 87 D....r.7O.+..P..
0020 - 91 0a a2 d2 28 b9 00 00-16 ....(....
002a - <SPACES/NULS>
read from 00988EB0 [00990AB8] (5 bytes => 5 (0x5))0000 - 16 03 01 02 05 .....
read from 00988EB0 [00990ABD] (517 bytes => 517 (0x205)) 0000 - 0b 00 02 01 00 01 fe 00-01 fb 30 82
01 f7 30 82 ..........0 ..................................................................................... 0.
0010 - 01 60 02 01 01 30 0d 06-09 2a 86 48 86 f7 0d 01 .`...0...*.H....
Server certificate
-----BEGIN CERTIFICATE-----
MIIB9zCCAWACAQEwDQYJKoZIhvcNAQEEBQAwTTELMAkGA1UEBhMCVVMxEDAOBgNV
BAsTB3Rlc3QxMDExDDAKBgNVBAMTA2NoYzEeMBwGCSqGSIb3DQEJARYPY2hjQHRl
c3QxMDEuY29tMB4XDTA0MDIyNjA2NTY1NFoXDTA1MDIyNTA2NTY1NFowOzELMAkG
A1UEBhMCVVMxDDAKBgNVBAMTA2NoYzEeMBwGCSqGSIb3DQEJARYPY2hjQHRlc3Qx
MDEuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDN5J58ttI0TtNTRiXH
U4glYOZG22Q6c2GSrCOSzSyUqY/Gf0dzwNmNNLcs3cmGvYJvzqzY4roP5fU6ZyyJ
GhsD6yGFKOMpmITtRnWC+g8wo6mlcUZM1g0XxBn9RPviGEamnauR3muhf/4wBihd
2NMpAMMdTBMAYY/zhVH1aNhpJQIDAQABMA0GCSqGSIb3DQEBBAUAA4GBACn9v1rt
cI9TpOkUTF66hMZUG/LAPMQwD38SgE4Bt/05UPFBDdiqd9mHJRoe4peIT1N1yHAi
agFhD1E+ExmcZPJ2FOiFJSOiEcSM+CMs0cPTcTrmcVQQB9xy/+7oPs+Od3Ppn/Wa
kGBNoKoDMh8Rby6aXzx3BSIMgb8plq3LOxiu
-----END CERTIFICATE-----
subject=/C=US/CN=chc/[email protected]
issuer=/C=US/OU=test101/CN=chc/[email protected]
Bytes Len Value Description
00 1 16 Record Content Type - Handshake Message
01-02 2 03 01 SSL version - TLSv1
03-04 2 00 2a Record Length
05 1 02 00 Handshake Type - Server_Hello
06-08 3 00 26 Message Length

37
09-0A 2 03 01 Protocol Version Chosen - TLSv1
Certificate
The certificate message consists of a chain of X.509 certificates in the correct order. The first certificate
belongs to the server, and the next certificate contains the key that certifies the first certificate (i.e., the
server's certificate), and so on. The client uses the server's public key (contained inside the server's
certificate) to either encrypt the pre_master_secret or verify the server_key_exchange, depending on which
ciphersuit is used.
No client certificate CA names sent
---
SSL handshake has read 1031 bytes and written 292 bytes
---
New, TLSv1/SSLv3, Cipher is EDH-RSA-DES-CBC3-SHA
Server public key is 1024 bitSSL-Session:
Protocol : TLSv1
Cipher : EDH-RSA-DES-CBC3-SHA
Session-ID:
Session-ID-ctx:
Master-Key: 57FDDAF85C7D287F9F9A070E8784A29C75E788DA2757699B
20F3CA50E7EE01A66182A71753B78DA218916136D50861AE
Key-Arg : None
Start Time: 1078211879 Timeout : 7200 (sec) Verify return code: 0 (ok)
---

Bytes Len Value Description


00 1 14 Record Content Type - Change_Cipher_Spec
01-02 2 03 01 SSL version - TLSv1
03-04 2 00 01 Record Length
05 1 01 ??

Certificate_Verify

Change_Cipher_Spec
Unknown Handshaking Message (D4) - to check
Application_Data

Client-to-Server - the HTTP request message: GET /test.html HTTP/1.0

Server-to-Client - the HTTP response message


Alert

RESULT:

Thus the confidentiality and Integrity using SSL was verified.

38
EX.NO.6 EXPERIMENT EAVESDROPPING, DICTIONARY ATTACKS, MITM ATTACKS

Aim:
To experiment eavesdropping, Dictionary attacks, MIMT attacks.

PROCEDURE
Password cracking is a term used to describe the penetration of a network, system, or resource with or
without the use of tools to unlock a resource that has been secured with a password. Password cracking
tools may seem like powerful decryptors, but in reality are little more than fast, sophisticated guessing
machines.

Types of password breaking

Dictionary attack
A simple dictionary attack is usually the fastest way to break into a machine. A dictionaryfile (a text
file full of dictionary words) is loaded into a cracking application, which is run against user accounts
located by the application.
Brute force attack
A brute force attack is a very powerful form of attack, though it may often take a long time to work
depending on the complexity of the password. The program will begin trying any and every combination
of numbers and letters and running them against the hashed passwords.
Passwords that are composed of random letters numbers and characters are most vulnerableto this type of
attack.
Hybrid attack
Another well-known form of attack is the hybrid attack. A hybrid attack will add numbers or symbols to
the search words to successfully crack a password. Many people change their passwords by simply
adding a number to the end of their current password. Therefore, this type of attack is the most versatile,
while it takes longer then a standard dictionary attack it does not take as long as a brute force attack.
Cracking Process
Since a brute force attack is the most time consuming and is not likely to break any passwords that are
not composed of random characters, the best plan is to use techniques that are computationally efficient
compared to untargeted and unspecific techniques. By applying what is known about how users select
passwords, an intruder can tremendously increase the odds in their favor of finding passwords. With the
right techniques, some poor passwords can be cracked in under a second.
The real power of dictionary attacks come from understanding the ways in which most people vary
names and dictionary words when attempting to create a password. By applying all the common
transformations to every word in the electronic list and encrypting each result the number tested
passwords multiplies rapidly. Cracking tools can often detect “clever” ways of manipulating words to
hide their origin. For example, such cracking programs often subject each word to a list of rules. A rule
could be anything, any manner in which a word might appear. Typical rules might include Alternate
upper- and lowercase lettering.
Spell the word forward and then backward, and then fuse the two results (for example:cannac). Add
the number 1 to the beginning and/or end of each word.

39
Naturally, the more rules one applies to the words, the longer the cracking process takes.However, more
rules also guarantee a higher likelihood of success.
Man in the Middle (MITM) against Diffie-Hellman:

A malicious Malory, that has a MitM (man in the middle) position, can manipulate the
communications between Alice and Bob, and break the security of the key exchange.
Step by Step explanation of this process:
Step 1: Selected public numbers p and g, p is a prime number, called the “modulus” and g is called the
base.
Step 2: Selecting private numbers.
let Alice pick a private random number a and let Bob pick a private random number b, Malory picks 2
random numbers c and d.

Step 3: Intercepting public values,


Malory intercepts Alice’s public value (ga(mod p)), block it from reaching Bob, and instead sends Bob
her own public value (gc(modp)) and Malory intercepts Bob’s public value (gb(mod p)), block it from
reaching Alice, and instead sends Alice her own public value (gd (modp))

Step 4: Computing secret key


Alice will compute a key S=gda(mod
1 p), and Bob will compute a different key,2=g(mod
S cb p)

Step 5: If Alice uses S1 as a key to encrypt a later message to Bob, Malory can decrypt it, re-encrypt it
using S2, and send it to Bob. Bob and Alice won’t notice any problem and may assume their
communication is encrypted, but in reality, Malory can decrypt, read, modify, and then re-encrypt all
their conversations.

Task 1 – Microsoft Office Password Recovery


Many applications require you to establish an ID and password that may be saved and automatically
substituted for future authentication. The password will usually appear on the screen as a series of asterisks.
This is fine as long as your system remembers the password for you but what if it "forgets" or you need it
for use on another system. Fortunately, many utilities have been written to recover such passwords. In this
task, you will use OfficeKey to recover the password for a MS word document.

40
You will find OfficeKey and a MS document in the folder.
Step 1: Find the folder “Lab1” on your desktop, and open it.

Step 2: Open the Office Key – Password Recovery tool


Step 3: Press the “Recover” button in the upper left corner, or select File
Recover
Step 4: Choose the password protected MS Office File you have saved to the Desktop.
Step 5: After running the first password auditing session, check to see if Office key has cracked the
password. If the password has not been cracked press the Settings button on the upper tool bar.

Step 6: Once in the Settings menu you will be able to modify the search parameters andcustomize a more
targeted search

41
Step 7: Repeat steps 3 and 4 until the password has been cracked and opens the MS Office File.

Step 8:Write down the contents of the MS word document and the password into your lab reportand submit
it to your TA.
Task 2 – Password Auditing (Windows platform):
The purpose of this task is to familiarize you with act of password cracking/recovery. Password cracking
software uses a variety of approaches, including intelligent guessing, dictionary attacks and automation that
tries every possible combination of characters. Given enough time the automated method can crack any
password, but more effective passwords will last months beforebreaking.
When a password is entered and saved on a computer it is encrypted, the encrypted password becomes a
string of characters called a “hash” and is saved to a password file. A password cannot be reverse-
decrypted. So a cracking program encrypts words and characters given to it (wordlist or randomly generated
strings of characters) and compares the results with hashed passwords. If the hashes match then the
password has successfully been guessed or “cracked”. This process is usually performed offline against a
captured password file so that being locked out of the account is not an issue, and guessing can go on
continuously. Thus, revealing the passwords is simply a mater of CPU time and dictionary size
1. You obtain a dictionary file, which is no more than a flat file (plain text) list of words (commonly
referred to as wordlists).
2. These words are fed through any number of programs that encrypt each word. Suchencryption conforms
to the DES standard.
3. Each resulting encrypted word is compared with the target password. If a matchoccurs, there is better
than a 90 percent chance that the password was cracked.
Step 1: Go to Lab1 folder, and open LC4 to audit the passwords on your Windows system.

New Session

Select File
Import from PWDUMP File (in the same folder)Select the “Passwords”
Select Import
file that has been provided to you.
42
Objectives This password file has been retrieved from a system that we must gain access to. To do this
you must crack as many passwords as possible as quickly as possible. We have captured the user names
and encrypted passwords for ten users. The user names follow a standard pattern of first initial and last
name, but the passwords have no set standards. We do know that users of this system are encouraged to
add numbers and
other characters to the words they chose for passwords.
To aid you in cracking these passwords we have managed to collect some basic information about the
users. This personal information may help you target your searches as to what the user’s password may
be.

Kmiller Ken Miller is an avid fly fisher and his record number of catch
is just under 30
Steven MacMan has a fiancé who’s name is 4 letters long a
Smacman starts with a “K”
Gkoch Gina Koch grew up with her German grandmother, who used
call her ‘Little Precious’ *
Matt Jones was born in 1979. He compares himself to
Mjones Shakespearean character who was born via C section
Tim Griffin loves funky ‘70’s and ‘80s music. And son
Tgriffin about ‘Love’
Ryan Klatt is a big Star Trek fan and has most likely chos
Rklatt an obscure reference for his password *

Step 2: Select Session Session Options

Use this menu to customize your password search. Here you can add different word list for Dictionary
attacks, change Hybrid attack features. Keep in mind you are working with a short dead line and more in
depth searches will take longer then you have. You must use the information given to you to target your
search most specifically at more likely passwords.

43
Step 3: Select Session Begin “Audit” or Press the blue play button on the upper toolbar to start the
password search. Step 4: After the first search has run check your progress. Have some of the passwords
been crackedall the way though or have some only been partially cracked. Use what you’ve learned from
this first search to target your next few searches. You will need to search the internet and use the
information you have been given about each user to find words they may have usedas their password.
Note: The question marks in the partially cracked passwords do not necessarily represent the number of
remaining undiscovered characters.
Step 5: Add words to your wordlistSession Session Options
Press the ‘Dictionary List’ button in the Dictionary crack section. Here you can edit your current word
list

and add words by selecting the ‘EDIT’ button and entering each wordona new line. You can also add
multiple dictionaries and wordlist.
Step 6:You may chose to conduct dictionary attacks with other wordlists.
You can findadditional wordlist to use here: ftp://ftp.cerias.purdue.edu/pub/dict
Step 7: Continue searching for possible passwords during the remainder of the lab. Repeating steps 3and 4
each time you modify your search.
44
Step 8: Once you have cracked all the passwords in the file, write them down in your lab report or once the
lab time has ended, submit the passwords you were able to crack.

Dictionary attacks,
import java.security.*;
import java.io.*;
import java.util.*;
import java.lang.StringBuilder;
import javax.xml.bind.DatatypeConverter;
public class DictionaryAttack {

//Extracted from http://www.jmdoudoux.fr/java/dej/chap-jca.htm


public static String bytesToHex(byte[] b) {
char hexDigit[] = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
StringBufferbuf = new StringBuffer();
for (int j=0; j<b.length; j++) {
buf.append(hexDigit[(b[j] >> 4) & 0x0f]);
buf.append(hexDigit[b[j] & 0x0f]);
}
return buf.toString();
}

//This method takes a string, computes its SHA-1 hash,


//and converts it into HEX using the bytesToHex method
public static String stringToSha1(String input) throws Exception {
//Setup a MessageDigest for SHA1
MessageDigest md = MessageDigest.getInstance("SHA1");
md.reset();
//Setup the MessageDigest with our input string

md.update(input.getBytes("UTF-8"));

//Convert the string's digest to HEX


String sha1 = bytesToHex(md.digest());
return sha1;
}
//This method takes a byte array holding a salt and a string input
//and returns the concatenated salt || input in byte array format
public static byte[] concatenate_salt_with_string(byte[] salt, String input) throws Exception {
//Convert input string to bytes
byte[] input_byte = input.getBytes("UTF-8");
//Create byte array sufficiently large
byte[] concatenated = new byte[salt.length + input_byte.length];
//Insert the salt first

45
System.arraycopy(salt, 0, concatenated, 0, salt.length);
//Insert the input string converted to bytes
System.arraycopy(input_byte, 0, concatenated, salt.length, input_byte.length);
//Return the concatenated salt and string in a byte array
return concatenated;
}
//This method takes a string, a salt, computes its salted SHA-1 hash,
//and converts it into HEX using the bytesToHex method
public static String stringToSha1_salted(byte[] salt, String input) throws Exception {
//Setup a MessageDigest for SHA1
MessageDigest md = MessageDigest.getInstance("SHA1");
md.reset();
//Use the concatenate_salt_with_string method to concatenate the salt with the input
byte[] concatenated = concatenate_salt_with_string(salt, input);
//Setup the MessageDigest with our input string

md.update(concatenated);

//Convert the string's digest to HEX


String sha1 = bytesToHex(md.digest());
return sha1;
}
public static void main(String[] args) throws Exception {
//Notify the user the program is starting.
System.out.println("Let's get things started.");

//Load the provided password file into stream and buffer


File passwords_file = new
File("/Users/nicolas/Documents/eclipseworkspace/dictionaryattack/src/password.txt");
FileInputStreampassword_stream = new FileInputStream(passwords_file);
BufferedReaderpassword_buffer = new BufferedReader(new InputStreamReader(password_stream));

//Initialize 3 hashmaps, one for non-salted passwords, one for salted passwords,
//and one for the salts of salted passwords.
Map<String, String>non_salted_passwords = new HashMap<String, String>();
Map<String, String>salted_passwords = new HashMap<String, String>();
Map<String, String>salted_passwords_salts = new HashMap<String, String>();

//We parse the buffer to extract user account names and passwords
String password_file_line = null;
while ((password_file_line = password_buffer.readLine()) != null) {
String[] splited = password_file_line.split("\\s+");
//First case: password hashed with no salt

46
if(splited.length == 3){
non_salted_passwords.put(splited[0], splited[2]);
}
//Second case: password hashed with a salt
else{
salted_passwords.put(splited[0], splited[3]);
salted_passwords_salts.put(splited[0], splited[2]);
}
}
//We are done reading the password file, we can close its buffer
password_buffer.close();

//Load the provided Dictionary into stream and buffer


File fin = new File("/Users/nicolas/Documents/eclipseworkspace/dictionaryattack/src/english.0");
FileInputStreamfis = new FileInputStream(fin);

//Construct BufferedReader from InputStreamReader


BufferedReaderbr = new BufferedReader(new InputStreamReader(fis));
//We parse the buffer to test matches for hashed password,
//reversed passwords, non vowel passwords, and salted versions of password (if required).
String line = null;
while ((line = br.readLine()) != null) {
//We first iterate through the non salted passwords
Iterator non_salted_passwords_it = non_salted_passwords.entrySet().iterator();
while (non_salted_passwords_it.hasNext()) {
//We extract the key,value pair from the HashTable entry
Map.Entry pair = (Map.Entry)non_salted_passwords_it.next();
String account_name = pair.getKey().toString();
String account_password_hash = pair.getValue().toString();

//We test if the password matches an unmodified dictionary entry


if(account_password_hash.equals(stringToSha1(line))){
System.out.println(account_name + "'s password is '" + line + "'");
}

//We test if the password matches a reversed dictionary entry


String reversed_line = new StringBuilder(line).reverse().toString();
if(account_password_hash.equals(stringToSha1(reversed_line))){
System.out.println(account_name + "'s password is '" + reversed_line + "'");
}

//We test if the password matches a dictionary entry without its vowels
String line_without_vowels = line.replaceAll("[AEIOUaeiou]", "");
if(account_password_hash.equals(stringToSha1(line_without_vowels))){
47
System.out.println(account_name + "'s password is '" + line_without_vowels +
"'"); } }
//We then iterate through the salted passwords
Iterator salted_passwords_it = salted_passwords.entrySet().iterator();
while (salted_passwords_it.hasNext()) {

//We extract the key,value pair from the HashTable entry


Map.Entrysalted_pair = (Map.Entry)salted_passwords_it.next();
String account_name = salted_pair.getKey().toString();
String account_password_hash = salted_pair.getValue().toString();
//We extract the corresponding salt from the HashTable of salts
byte[] account_password_hash_salt =
DatatypeConverter.parseHexBinary(salted_passwords_salts.get(account_name));

//We test if the password matches an unmodified dictionary entry


if(account_password_hash.equals(stringToSha1_salted(account_password_hash_salt,line))){
System.out.println(account_name + "'s password is '" + line + "'");
}

//We test if the password matches a reversed dictionary entry


String reversed_line = new StringBuilder(line).reverse().toString();
if(account_password_hash.equals(stringToSha1_salted(account_password_hash_salt,reversed_line))){
System.out.println(account_name + "'s password is '" + reversed_line + "'");
}

//We test if the password matches a dictionary entry without its vowels
String line_without_vowels = line.replaceAll("[AEIOUaeiou]", "");
if(account_password_hash.equals(stringToSha1_salted(account_password_hash_salt,line_without_vowels))
){
System.out.println(account_name + "'s password is '" + line_without_vowels + "'");
}
}
}
//We are done using the dictionary file, we can close its buffer
br.close();
//Notify the user our program is done running.
System.out.println("The program terminated.");
}

}
Password.txt
andrew 0 7207aa5e5e68188241a72b3fd9b12391585cad21
joe 0 65640c6577c9c72497525e656127b5bd1deb6f85
eve 0 61424ee758ec5e0d0ffe6a2ce151bf9d927c3ad7

48
bob 0 843b961da8707a9314aa3b7bb950a7003e49a94c
guy 0 eb6dc8cf797e6aeec2f2695883c0cf93cc765537
alice 0 eb756abf97413f28b2e36f1de57e17b31129aa46
mary 0 932eeb1076c85e522f02e15441fa371e3fd000ac
adam 0 7d27662bb31cb629178e929287993c01bf7c42ac
nick 1 a9edd3db 93bbd7dab6e365a5a840584d9849cbd55fbbf469
john 1 2afd4f21 511c896b5bcf313140d513100966a5ccec90c714
Here are the files you can find in this repository:
 password.txt contains a list of passwords that we recover using the attack
 DictionaryAttack.java is the source code for the attack

english.0 is the dictionary used during the attack to recover passwords
Description of the password.txt file format
The list of passwords that we recover using the attack is a text file in which each line contains a user
account name followed by a password. There are two possible line formats: the first one contains
an unsalted password while the second contains a salted password along with the salt.
username 0 unsaltedpassword
username 1 salt saltedpassword
The passwords are hashed using SHA-1 (see attack source code for implementation in the Java
Cryptography Extension). When a salt is used, it is simply concatenated together with the
passwords as follows: salt || password.
Description of the attack
The attack simply reads the dictionary line by line and computes 6 different possible hashed
passwords for the word contained in each line. These 6 possible hashes are compared to each of
the passwords contained in the password.txt file for a match. If there is a match, we recovered a
password. If not, we simply keep reading the dictionary line by line.
The 6 possible hashes computed for each word from the dictionary are:
 SHA1(word)
 SHA1(drow) (reversed word)


SHA1(wrd) (word without vowels)
 SHA1(salt||word) (salted word)
 SHA1(salt||drow) (salted reversed word)
SHA1(salt||wrd) (salted word without vowels)
Note that the salts used in salted hashes are the ones includes in the password.txt file.
How to run the attack
To run the attack, simply compile and run the DictionaryAttack.java file. All paths are hardcoded in
the file so you will need to update them before you compile the source code.
The output should be the following:
Let's get things started.
joe's password is 'December'
alice's password is 'tfosorciM'
mary's password is 'Monday'
john's password is 'brosba'
bob's password is 'yllacitebahpla'
guy's password is 'ntrstwrthnss'
nick's password is 'uplifting'
adam's password is 'vsblts'

49
eve's password is 'wrrsm'
andrew's password is 'kcitsdray'
The program terminated.
Note on complexity
Note that this attack is a simple example and could be made far more efficient using various
strategies. One of them would be to precompute the possible hashes before checking the password list
for matches. Since our password list and dictionary are fairly small in this example, I did not
implement this feature.

RESULT:

Thus the experiment for Eavesdropping, Dictionary attacks, MITM attacks was done successfully

50
EX.NO. 7 PERFORM AN EXPERIMENT TO SNIFF TRAFFIC USING ARP POISONING.

AIM:
Perform an Experiment to Sniff Traffic using ARP Poisoning.
PROCEDURE
Address Resolution Protocol (ARP) poisoning is a type of attack where the Media Access Control
[MAC] address by the attacker called spoofing. ARP poison routing uses the stored cache as a way to
reroute or redirect ;packets from a target, to an intermediate machine. Thus MAN in MIDDLE watch
the traffic between Source and Target machines.

To perform this Install CAIN and Abel tool and do the following:
Click on Sniffer menu.
Click on hosts on the button portion window.
Click Start sniffer and APR service from Standard toolbar menu

51
Right Click on the hosts window and click on Scan MAC address.
Select all hosts in my subnet or range FROM and TO IP address and Click OK.
Now you view the MAC and IP address of Remote / Local machines.
Click on APR button on toolbar menu.
Left Click on right pane of APR window and then Click on ‘+’ symbol on standard toolbar.
APR enables you to poison IP traffic between the selected host .
Click on any IP address on the left side list and the other IP selected on the right side.
 Left Click on Right side on the IP address and Click OK.
Wathch the poisoning effect FROM and TO IP address

52
The analysis of this traffic can also be performed by other tool called ETHEREAL

ABEL is the second part of program composed by two files able.exe and abel.dll. The service can be
installed with Administrative Priviledges on the Target Machine.
Execute Abel.exe from ProgramFiles Folder.
Expand Microsoft windows Network and Click on all Computers.
Right Click on Computer and Connect as Administrative Credentials.
Once connected Right Click on services icon and select install Abel, the two files abe.exe and
abel.dll will be copied on to connected Computer.
Now bring up a console prompt on the connected Computer examine the password hashes.

RESULT:

Thus the experiment to Sniff Traffic using ARP Poisoning was performed.

53
EX.NO.8 DEMONSTRATE INTRUSION DETECTION SYSTEM (IDS)
AIM:

To demonstrate Intrusion Detection System(IDS) using Snort software tool.

PROCEDURE:
STEPS ON CONFIGURING AND INTRUSION DETECTION:

o Download Snort from the Snort.org website. (http://www.snort.org/snort-downloads)


o Download Rules(https://www.snort.org/snort-rules). You must register to get the rules. (You should
o
o download these often)
o Double click on the .exe to install snort. This will install snort in the “C:\Snort” folder.It isimportant to
have WinPcap (https://www.winpcap.org/install/) installed
o
Extract the Rules file. You will need WinRAR for the .gz file.
o
Copy all files from the “rules” folder of the extracted folder. Now paste the rules into
“C:\Snort\rules” folder.
Copy “snort.conf” file from the “etc” folder of the
extracted folder. You must paste it into “C:\ Snort\etc” folder. Overwrite any existing file.
Remember if you modify your snort.conf file and download a new file, you must modify it for
Snort to work.

cd\snort\bin)

o Open a command prompt (cmd.exe) and navigate to folder “C:\Snort\bin” folder. ( at the Prompt,type
o To start (execute) snort in sniffer mode use following command:
snort -dev -i 3
-i indicates the interface number. You must pick the correct interface number. In my case, it is 3.
-dev is used to run snort to capture packets on your network.

To check the interface list, use following command:snort –W

54
Finding an interface

You can tell which interface to use by looking at the Index number and finding Microsoft. As you cansee in
the above example, the other interfaces are for VMWare.
To run snort in IDS mode, you will need to configure the file “snort.conf” according to your network
environment.
To specify the network address that you want to protect in snort.conf file, look for the following line. var
HOME_NET 192.168.1.0/24 (You will normally see any here)
You may also want to set the addresses of DNS_SERVERS, if you have some on your network.

Example:

example snort
Change the RULE_PATH variable to the path of rules folder.var RULE_PATH c:\snort\rules
path to rules
Change the path of all library files with the name and path on your system. and you must change thepath
of snort_dynamicpreprocessorvariable.
C:\Snort\lib\snort_dynamiccpreprocessor
You need to do this to all library files in the “C:\Snort\lib” folder. The old path might be: “/usr/local/lib/…”.
you will need to replace that path with your system path. Using C:\Snort\lib
Change the path of the “dynamicengine” variable value in the “snort.conf” file..

Example:
Dynamic engine C:\Snort\lib\snort_dynamicengine\sf_engine.dll
Add the paths for “include classification.config” and “include reference.config” files. include
c:\snort\etc\classification.config
include c:\snort\etc\reference.config
Remove the comment (#) on the line to allow ICMP rules, if it is commented with a #. include
$RULE_PATH/icmp.rules
You can also remove the comment of ICMP-info rules comment, if it is commented. include
$RULE_PATH/icmp-info.rules
To add log files to store alerts generated by snort, search for the “output log” test in snort.conf andadd the
55
following line:
output alert_fast: snort-alerts.ids
Comment (add a #) the whitelist $WHITE_LIST_PATH/white_list.rules and the blacklist

Change the nested_ip inner , \ to nested_ip inner #, \Comment out (#) following lines:

#preprocessor normalize_ip4
#preprocessor normalize_tcp: ips ecn stream#preprocessor normalize_icmp4 #preprocessor normalize_ip6
#preprocessor normalize_icmp6
Save the “snort.conf” file.
To start snort in IDS mode, run the following command:
snort -c c:\snort\etc\snort.conf -l c:\snort\log -i 3(Note: 3 is used for my interface card)

If a log is created, select the appropriate program to open it. You can use WordPard or NotePad++ toread the
file.
To generate Log files in ASCII mode, you can use following command while running snort in IDSmode:
snort -A console -i3 -c c:\Snort\etc\snort.conf -l c:\Snort\log -K ascii

Scan the computer that is running snort from another computer by using PING or NMap (ZenMap).

After scanning or during the scan you can check the snort-alerts.ids file in the log folder to insure it islogging
properly. You will see IP address folders appear.
Snort monitoring traffic

RESULT:

Thus the Intrusion Detection System(IDS) has been demonstrated using the Open Source Intrusion
Detection Tool Snort.

56
EX.NO:9 NETWORK MONITORING TOOLS

AIM:
To explore about Network monitoring tools.
PROCEDURE

Network monitoring is an essential part of network management. It involves using various tools to monitor a
system network and determine slowness and weak connections, among other issues. Knowing more about
these tools can help you understand them better and use the right ones that suit your requirements. In this
article, we define what network monitoring tools are, provide details about various tools and discuss about
some tips that can help you choose the right tool for your requirements.

What Are Network Monitoring Tools?

Network monitoring tools are software that you can use to evaluate network connections. These software
programs can help you monitor a network connection and identify network issues, which mayinclude failing
network components, slow connection speed, network outage or unidentifiable connections. Network
management and monitoring tools can also help you resolve these issues or establish solutions that prevent
specific issues from occurring in the future.

Here are eight monitoring tools along with their descriptions and features:

1. SolarWinds Network Performance Monitor

SolarWinds Network Performance Monitor is a multi-vendor monitoring tool. It allows users to monitor
multiple vendors' networks at the same time. It also provides network insights for thorough visibility into
the health of the networks. Some prominent features include network availability monitoring, intelligent
network mapping, critical path visualisation, performance analysis and advanced alerting. SolarWinds also
allows users to track VPN tunnel status. It prompts when a VPN tunnel is available to help users ensure a
stable connection between sites. SolarWinds provides a seven-day free trial, after which users can choose
a preferred subscription plan.

2. Auvik

Auvik is a network monitoring and management tool. It offers a quick implementation process that helps
users to set up the tool easily. It also has a clean user interface that makes it easy to navigate and use. The
tool provides in-depth network visibility that enables faster troubleshooting for network issues. Users can
automate network visibility using Auvik. It provides real-time updates on network issues and configuration
changes.

3. Datadog Network Monitoring

Datadog Network Monitoring offers services for on-premises devices and cloud networks. A highlighting
feature of this tool is the visualisations. It offers various graphical representations of all the network
connections on a system. It also allows users to track key metrics like network latency, connection churn

57
and transmission control protocol (TCP) retransmits. Users can monitor the health of a network
connection at different endpoints at the application, IP address, port or process ID layers. Other prominent
features include automated log collection and user interface monitoring.
4. Paessler PRTG Network Monitor

Paessler's network connection monitoring tool provides a clean user interface and network visibility on
multiple devices. Users can track the health of different connection types like local area networks (LAN),
wide area network (WAN), servers, websites, applications and services. The tools also integrate with
various technologies, which makes it easier to use it for different types of applications. It provides distribute
monitoring, allowing users to track network connections on devices in different locations. The tool also
provides apps for mobile platforms that can help users to track network health on mobile phones.
5. ManageEngine OpManager

ManageEngine OpManager is a good network monitoring and managing tool for users that prefer in-

depth
view of network health and issues. This tool provides over 2000 network performance monitors that allow
users to track and monitor their connections and perform detailed analyses on issues. It also provides over
200 dashboard widgets that can help users customise their dashboard to their own suitability. Other features
include CPU, memory and disk utilisation monitoring on local and virtual machines. It also allows setting
network performance threshold and notifies the user in case of a violation.
6. Domotz

Domotz is an expansive tool that provides a list of features for monitoring network connections. It allows
users to customise their network monitoring preferences. Users can write scripts the retrieve the data they
wish to evaluate. It also allows connection to open ports on remote devices while ensuring network security.
Users can also scan and monitor network connections globally. Domotz also allows to backup and restore
network configuration for switches, firewalls and access points and alerts when there is a change in the
configuration.
7. Checkmk

Checkmk is a tool that allows users to automate it completely. You can customise its operations and enable
it to perform tasks automatically. It also identifies network and security components without the user
requiring manual set up. For example, the tool can identify a firewall even if the user has not set it up. Its
Agent Bakery feature enables users to manage agents and automate agent updating. This reduces manual
effort to monitor network connections. The tool also includes over 2000 plug-ins for enhancing network
monitoring.
8. Progress Whatsup Gold

Progress Whatsup Gold is a basic network monitoring software. It provides a minimal user interface with
essential features like device monitoring, application monitoring, analysing network traffic and managing
configurations. The tool allows users to monitor cloud devices, inspect suspicious connections, automate
configuration backups and identify, and resolve bandwidth issues.

58
Other Tools For Network Monitoring Here are three additional tools for network monitoring:
Fortra
allowingIntermapper: This tool enables users to monitor network connections using network maps,
them to get a holistic view of all the connections. It also provides various colour codes for different network
status, along with real-time notifications through text, email and sound.
Nagios Core: Nagios Core is a monitoring engine that works as the primary application for all Nagios
projects, including the Nagios Network Analyser. It integrates with other Nagios applications and provides
users with features like a visual dashboard, custom applicationmonitoring, automated alert system, advanced
user management and network security monitoring.
Zabbix: Zabbix provides a thorough network monitoring solution with features like server monitoring, cloud
monitoring, application monitoring and service monitoring. The tool also includes features like metric
collection, business monitoring and root cause analyses of network issues, and allows users to establish a
threshold for connection anomalies.
To Choose A Network Monitoring And Management Tool

Here are some useful tips that you can consider while selecting a tool for network monitoring:

Understand the requirements

Understanding why you require network monitoring software is important in the process. Define what
feature you want and for what purpose. This can help you identify the right tool for your use. It may also
help you choose the correct subscription plan on paid tools.

Browse multiple tools

Once you identify the requirements, consider browsing multiple tools. Visit the websites of the tools and
look for the features you require. Spend time studying the features and understand how they can beuseful to
your requirements. You can also identify a few tools and compare their features to each other.

Consider the budget

Some tools may be free to use, while some may require you to purchase a subscription plan. Paid tools
typically offer a free trial period of up to 30 days. Once you identify which tool you may like to use, see if
it is free or requires payment. If it is a paid tool, try exploring its features and efficiency during the trial
period. Consider keeping a backup tool in case the tool that you choose does not fit your usage.

RESULT:
59
Thus the network monitoring tools was explored.
EX. NO.10 CONFIGURE FIREWALL, VPN
AIM: To study the features of firewall in providing network security and to setFirewall Security in windows.

PROCEDURE :

Firewall in Windows 7

Windows 7 comes with two firewalls that work together. One is the Windows Firewall, and the other is
Windows Firewall with Advanced Security (WFAS). The main difference between them is the
complexity ofthe rules configuration. Windows Firewall uses simple rules that directlyrelate toa program or
a
service. The rules in WFAS can be configured based on protocols, ports, addresses and authentication. By
default, both firewalls come with predefined set of rules that allow us to utilize network resources. This
includes things like browsing the web, receiving e-mails, etc. Other standard firewall exceptions are File and
Printer Sharing, Network Discovery, Performance Logs and Alerts, Remote Administration, Windows
Remote Management, Remote Assistance, Remote Desktop, Windows Media Player, Windows Media
Player
Network Sharing Service
With firewall in Windows 7 we can configure inbound and outbound rules. By default, all outbound traffic
is
allowed, and inbound responses to that traffic are also allowed. Inbound traffic initiated from external
sources
is automatically blocked.
When we first connect to some network, we are prompted to select a network location. This feature is
known
as Network Location Awareness(NLA). This feature enables us to assign a network profile to the
connection
based on the location. Different network profiles contain different collections of firewall rules. In Windows 7,
different network profiles can be configured on different interfaces. Forexample, our wired interface can
have
different profile than our wireless interface. There are three different network profiles available:



Public
Configuring Windows Firewall
Home/Work - private network
Domain - used within a domain

To open Windows Firewall we can go to Start > Control Panel > Windows
Firewall.
60
By default, Windows Firewall is enabled for both private (home or work)and public networks. It is also
configured to block all connections to programs that are not on the list of allowed programs. To configure
exceptions we can go to the menu on the left and select "Allow a program or feature trough Windows
Firewall" option.
Exceptions

To change settings in this window we have to click the "Change settings" button. As you can see, here we
have a list of predefined programs and features that can be allowed to communicate on private or public
networks. For example, notice that the Core Networking feature is allowed on both private and public
networks, while the File and Printer Sharing is only allowed on private networks. We can also see the details
of the items in the list by selecting it and then clicking the Details button.

Details
If we have a program on our computer that is not in this list, we can manually add it by clicking on the
"Allow another program" button.
Add a Program
Here we have to browse to the executable of our program and then click the Add button. Notice that we can

61
also choose location types on which this program will be allowed to communicate by clicking on the
"Network location types" button. Network Locations
Many applications will automatically configure proper exceptions in Windows Firewall when we run
them.
For example, if we enable streaming from Media Player, it will automatically configure firewall settings
to
allow streaming. The same thing is if we enable Remote Desktop feature from thesystem properties
window.
By enabling Remote Desktop feature we actually create an exception in Windows Firewall.
Windows Firewall can be turned off completely. To do that we can select the "Turn Windows Firewall
on or
off" option from the menu on the left.
Firewall Customization

Note that we can modify settings for each type of network location (private or public). Interesting thing
here is
that we can block all incoming connections, including those in the list of allowed programs.
Windows Firewall is actually a Windows service. As you know, services can be stopped and started. If
the
Windows Firewall service is stopped, the Windows Firewall will not work.
Firewall Service

In our case the service is running. If we stop it, we will get a warning thatwe should turn on our

Windows Firewall. Warning Remember that with Windows Firewall we can only configure basic firewall

settings, and this is enough for


most day-to-day users. However, we can't configure exceptions based on ports in Windows Firewall any
more. For that we have to use Windows Firewall with Advanced Security.
How to Start & Use the Windows Firewall with Advanced Security
The Windows Firewall with Advanced Security is a tool which gives you detailed control over the rules
that
are applied by the Windows Firewall. You can view all the rules that are used by the Windows Firewall,
change their properties, create new rules or disable existing ones. In this tutorial we will share how to open
the
Windows Firewall with Advanced Security, how to find your way around it and talk about the types of
rules
that are available and what kind of traffic they filter.
How to Access the Windows Firewall with Advanced Security
62
You have several alternatives to opening the Windows Firewall with Advanced Security:

One is to open the standard Windows Firewall window, by going to "Control Panel -> System and Security ->
Windows Firewall". Then, click or tap Advanced settings.

In Windows 7, another method is to search for the word firewall in the Start Menu search box and click the
"Windows Firewall with Advanced Security" result.
In Windows 8.1, Windows Firewall with Advanced Security is not returned in search results and you need to
use the first method shared above foropening it.
The Windows Firewall with Advanced Security looks and works the same both in Windows 7 and Windows
8.1. To continue our tutorial, we will use screenshots that were made in Windows 8.1.

71
What Are The Inbound & Outbound Rules? In order to provide the security you need, the Windows

Firewall has a standard set of inbound and outbound


rules, which are enabled depending on the location of the network you are connected to.
Inbound rules are applied to the traffic that is coming from the network and the Internet to your
computer or
device. Outbound rules apply to the traffic from your computer to the network or the Internet.
These rules can be configured so that they are specific to: computers, users, programs, services, ports or
protocols. You can also specify to which type of network adapter (e.g. wireless, cable, virtual private
network) or user profileit is applied to.

In the Windows Firewall with Advanced Security, you can access all rulesand edit their properties. All you
have to do is click or tap the appropriate unit in the left-side panel.

The rules used by the Windows Firewall can be enabled or disabled. The ones which are enabled or active
are marked with a green check-box in the Name column. The ones that are disabled are marked with a
gray check- box. If you want to know more about a specific rule and learn its properties, right click on it
andselect Properties or select it and press Properties in thecolumn on right, which lists the actions that are
available for your selection.

72
What Are The Connection Security Rules? Connection security rules are used to secure traffic between

two computers while it crosses the network. One


example would be a rule which defines that connectionsbetween two specific computers must be encrypted.
Unlike the inbound or outbound rules, which are applied only to one computer, connection security
rules
require that both computers have the same rules defined and enabled.
If you want to see if there are any such rules on your computer, click or tap "Connection Security Rules"
on
the
are panel on the left. By default, there are no such rules defined on Windows computers and devices. They
generally used in business environments and such rules are set by the network administrator.

2.1.1 Configuring Windows Firewall

To open Windows Firewall we can go to Start > Control Panel >

73
By default, Windows Firewall is enabled for both private (home or work) and public networks. It is also
configured to block all connections to programs that are not on the list of allowed programs. To configure
exceptions we can go to the menu on the left and select "Allow a program or feature trough Windows
Firewall" option.

Exceptions To change settings in this window we have to click the "Change settings" button. As you can
see, here we have a list of predefined programs and features that can be allowed to communicate on private
or public networks. For example, notice that the Core Networking feature is allowed on both private and
public networks, while the File and Printer Sharing is only allowed on private networks. We can also see
the details of the items in the list by selecting it and then clicking the Details button.
Details
If we have a program on our computer that is not in this list, we can

manually add it by clicking on the "Allow another program" button.

74
Add a Program Here we have to browse to the executable of our program and then click the Add button.
Notice that we can also choose location types on which this program will be allowed to communicate by
clicking on the "Network location types" button. Network Locations Many applications will
automatically configure proper exceptions in Windows Firewall when we run them. For example, if we
enable streaming from Media Player, it will automatically configure firewall settings to allow streaming.
The same thing is if we enable Remote Desktop feature from the system properties window. By enabling
Remote Desktop feature we actually create an exception in Windows Firewall. Windows Firewall can be
turned off completely. To do that we can select the "Turn Windows Firewall on or off" option from the
menu on the left.

Firewall Customization

Note that we can modify settings for each type of network location (private or public). Interesting thing here is
that we can block all incoming connections, including those in the list of allowed programs.

Windows Firewall is actually a Windows service. As you know, services can be stopped and started. If the
Windows Firewall service is stopped, the Windows Firewall will not work.

Firewall Service
In our case the service is running. If we stop it, we will get a warning thatwe should turn on our Windows
Firewall.

75
Warning

Remember that with Windows Firewall we can only configure basic firewall settings, and this is enough for
most day-to-day users. However, we can't configure exceptions based on ports in Windows Firewall any more.
For that we have to use Windows Firewall with Advanced Security.
How to Start & Use the Windows Firewall with Advanced Security
The Windows Firewall with Advanced Security is a tool which gives you detailed control over the rules that
are applied by the Windows Firewall.You can view all the rules that are used by the Windows Firewall,
change their properties, create new rules or disable existing ones. In this tutorial we will share how to open the
Windows Firewall with Advanced Security, howto find your way around it and talk about the types of rules
that are available and what kind of traffic they filter. How to Access the Windows Firewall with Advanced
Security
You have several alternatives to opening the Windows Firewall with Advanced Security:
One is to open the standard Windows Firewall window, by going to "Control Panel ->System and Security -
> Windows Firewall". Then, click or tap Advanced settings.

In Windows 7, another method is to search for the word firewall in the Start Menu searchbox and click the
"Windows Firewall with Advanced Security" result.

In Windows 8.1, Windows Firewall with Advanced Security is not returned in search results and you need to
use the first method shared above for opening it.
76
.

The Windows Firewall with Advanced Security looks and works the same both in Windows 7 and
Windows 8.1. To continue our tutorial, we will use screenshots that were made in Windows 8.
What Are The Inbound & Outbound Rules?

In order to provide the security you need, the Windows Firewall has a standard set of inbound and

outbound
rules, which are enabled depending on the location of the network you are connected to.
Inbound rules are applied to the traffic that is coming from the network and the Internet to your
computer or
device. Outbound rules apply to the traffic from your computer to the network or the Internet.
These rules can be configured so that they are specific to: computers, users, programs, services, ports or
protocols. You can also specify to which type of network adapter (e.g. wireless, cable, virtual private
network) or user profileit is applied to.
In the Windows Firewall with Advanced Security, you can access all rules and edit their properties. All
you have to do is click or tap the appropriate unit in the left-side panel.

77
The rules used by the Windows Firewall can be enabled or disabled. The ones which are enabled or active
are marked with a green check-box in the Name column. The ones thatare disabled are marked with a gray
check-box.If you want to know more about a specific rule and learn its properties, right click on it and
select Properties or select it and pressProperties in the column on right, which lists the actions that are
available for yourselection.

What Are The Connection Security Rules? Connection security rules are used to secure traffic between

two computers while it crosses the network. One


example
encrypted.would be a rule which defines that connections between two specific computers must be
Unlike the inbound or outbound rules, which are applied only to one computer, connection security rules
require that both computers have thesame rules defined and enabled.
If you want to see if there are any such rules on your computer, click or tap "Connection Security Rules"
on
the panel on the left. By default, there are no such rules
78 defined on Windows computers and devices. They
are generally used in business environments and such rules are set by the network administrator.
What Does the Windows Firewall with Advanced SecurityMonitor? The Windows Firewall with Advanced
Security includes some monitoring features as well. In the Monitoring section you can find the following
information: the firewall rules that are active (both inbound and outbound), the connection security rules
that are active and whether there are any active security associations.

You should note that the Monitoring section shows only the active rules for the current network location.

RESULT:

Study of the features of firewall in providing network security and to setFirewall Security in windows.

79
EX. NO. 11 Exploring N-Stalker, a Vulnerability Assessment Tool

AIM:
To download the N-Stalker Vulnerability Assessment Tool and exploring
the features.

PROCEDURE:

EXPLORING N-STALKER:
N-Stalker Web Application Security Scanner is a Web security assessment tool.
It incorporates with a well-known N-Stealth HTTP Security Scanner and 35,000 Webattack
signature database.
This tool also comes in both free and paid version.
Before scanning the target, go to “License Manager” tab, perform the update.Once
update, you will note the status as up to date.
You need to download and install N-Stalker from www.nstalker.com.

1. Start N-Stalker from a Windows computer. The program is installed under Start ➪
Programs ➪N-Stalker ➪N-Stalker Free Edition.
2. Enter a host address or a range of addresses to scan.
3. Click Start Scan.
4. After the scan completes, the N-Stalker Report Manager will prompt
5. you to select a format for the resulting report as choose Generate HTML.
6. Review the HTML report for vulnerabilities.
Now goto “Scan Session”, enter the target URL.
In scan policy, you can select from the four options,
Manual test which will crawl the website and will be waiting for manual attacks.full xss
assessment
owasp policy Web server infrastructure analysis.
Once, the option has been selected, next step is “Optimize settings” which will crawlthe
whole website for further analysis.

In review option, you can get all the information like host information, technologiesused, policy
name, etc

80
Once, the option has been selected, next step is “Optimize settings” which will crawlthe whole
website for further analysis.

In review option, you can get all the information like host information, technologiesused, policy name,
etc

83
Once done, start the session and start the scan.
The scanner will crawl the whole website and will show the scripts, broken pages,
hiddenfields, information leakage, web forms related information which helps to
analyze further.

84
Once the scan is completed, the NStalker scanner will show
details like severity level, vulnerability class, why is it an issue,
the fix for the issue and the URL whichis vulnerable to the
particular vulnerability?

RESULT:

Thus the N-Stalker Vulnerability Assessment tool has been downloaded,


installed and the features has been explored by using a vulnerable website.

85
EX.NO.12 CONFIGURING S/MIME FOR E-MAIL COMMUNICATION

AIM:
To configure S/MIME for e-mail communication.

PROCEDURE

Decryption process
1. The recipient receives the email.
2. The encrypted message is retrieved.
3. The recipient's private key is used to decrypt the encrypted message.
4. The original message is obtained and displayed to the recipient. Digital signing

process
1. Once the sender clicks on Send, the original message is captured.
2. The message hash is calculated.
3. The sender's private key is used to encrypt the hash value.
4. The encrypted hash value is added to the email.
5. The email is sent to the recipient.
Signature verification process
1. The recipient receives the digitally signed email.
2. The original message is obtained and its hash value is calculated.
3. The encrypted hash is retrieved from the email.
4. The encrypted hash is decrypted using the sender's public key.
5.
areThe decrypted hash and the hash value calculated from the original message obtained
compared. If the values match, the signature is verified.

How to Enable S/MIME Gmail:


1. Log into an Administrator Account. Non-admin accounts cannot open the admin
console needed to set up a hosted S/MIME encryption solution.
2. Go to User Settings. From the Admin console’s Home page, select Apps > G Suite >
Gmail > User Settings.
3. Select the Domain or Organization to Configure. This will be found on the left of the
screen, under Organizations.
4. Select the “Enable S/MIME” Box. There should be a box with the setting that you
can
enable with a click.
5. Allow Users to Upload Certificates (Optional). You can allow users to upload their
own S/MIME certificates as an option.
6. Set up Root Certificate Management (Optional). You can manage the root

certificates
used for S/MIME email encryption by: 1. Clicking Add next to Accept these additional
Root Certificates for specific domains.
2. Clicking on Upload Root Certificate.
86
3. Browsing to find the certificate file and selecting Open. A verification message should
appear. Otherwise, an error message may appear.
4. Under Encryption level, choose the encryption level to use with the selected certificate.
5. Under Address list, enter at least one domain that will use the uploaded root certificate.
6. Click Save.
7. Repeat these steps for each additional certificate chain.

Does Your Domain/Organization NEED to Enable Secure Hash Algorithm 1? If so,


you may need to select the Allow SHA-1 globally box. Otherwise, this is not
recommended by Google.

8. Click Save. Save your settings so they don’t get lost.


9. Have All Users Reload Gmail. After enabling hosted S/MIME Gmail encryption, users
will need to reload their Gmail client to see the change.
10. Upload S/MIME Certificates. You can upload personal S/MIME certificates in Gmail
if you:
1. Go to Settings.
2. Click on the Accounts tab.
3. Click on Edit Info in the Send mail as area. A window should appear with the
“enhanced encryption” option—if this was enabled in Step 5 listed above.
4. Click on Upload a personal certificate.
5. Select the certificate and click Open. A password prompt should appear if this works.
6. Enter the password and click on Add certificate.

11. Have Users Exchange S/MIME Keys. To decrypt encrypted messages, users in the
organization will need to exchange S/MIME encryption keys. This can be done by: 1.
Sending an S/MIME encrypted message to the recipient with a digital signature that
includes the user’s public key. This can then be used to send S/MIME-encrypted emails.
2. Asking recipients to send a message. The S/MIME signed message will allow the
encryption key to be automatically stored so future messages will be encrypted.

87
RESULT
S/MIME for e-mail communication is configured successfully.

88
INNOVATIVE PROJECT

ANALYSIS THE SECURITY VULNERABILITIES OF E-COMMERCE SERVICES

ABSTRACT

 Identify the vulnerabilities input validations and database servers.


 Point out the vulnerabilities in TCP/IP Protocols used for communications.
Security Vulnerabilities of E-commerce services:

Vulnerability is a weakness which allows an attacker to reduce a system's information


assurance. Vulnerability is the intersection of three elements: a system susceptibility or flaw,
attacker access to the flaw, and attacker capability to exploit the flaw. To exploit
vulnerability, an attacker must have at least one applicable tool or technique that can
connect to a system weakness

Some of the things that can be incorporated in SDLC are:

1. Software should be installed using security defaults


2. A software patch management process should be there.

89

You might also like