Ccs 354 Network Security Manual - PDF Edited2
Ccs 354 Network Security Manual - PDF Edited2
AIM:
To implement a Caesar cipher substitution technique in Java.
ALGORITHM:
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:
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) {
4
PLAYFAIR CIPHER OUTPUT C:\Users\abacussys1\Desktop>javac
Playfair Cipher
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:
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 ");
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:
"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)); } }
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;
}
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();
}
}
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:
PROGRAM:
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:
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
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:
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
AIM:
To implement RSA(Rivest–Shamir–Adleman) algorithm by using HTML and Javascript.
ALGORITHM:
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:
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:
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
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:
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.
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
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)
---
Certificate_Verify
Change_Cipher_Spec
Unknown Handshaking Message (D4) - to check
Application_Data
RESULT:
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.
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 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.
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 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 *
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 {
md.update(input.getBytes("UTF-8"));
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);
//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();
//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 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:
PROCEDURE:
STEPS ON CONFIGURING AND INTRUSION DETECTION:
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.
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.
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:
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.
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:
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.
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.
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
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
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
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
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
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:
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.
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.
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
ABSTRACT
89