You are on page 1of 82

211718104001

TABLE OF CONTENTS

S. No Date Particulars Page Signature


No.
1 Perform encryption, decryption using the following
substitution techniques
1.a Caesar Cipher 3

1.b Play fair Cipher 6


1.c Hill Cipher 11
1.d Vigenere Cipher 15
Perform encryption and decryption using following
2
transposition techniques
2.a Rail fence – row & Column Transformation 18
Implement the following algorithms

3 Apply DES algorithm for practical applications 22

4 Apply AES algorithm for practical applications 26

5 Implement RSA Algorithm using HTML and 30


JavaScript
6 Diffie-Hellman 35
7 Calculate the message digest of a text using the SHA- 38
1 algorithm.
8 Implement the SIGNATURE SCHEME - 40
Digital Signature Standard
Demonstrate intrusion detection system (ids) using 42
9 any tool (snort or any other s/w)
10 Automated Attack and Penetration Tools 47
Exploring N-Stalker, a Vulnerability Assessment
Tool
Defeating Malware
11 56
 Building Trojans
 Rootkit Hunter
Content Beyond the Syllabus
12
Pretty Good Privacy 61
13
Triple DES 64
14
Analysis the Security Vulnerabilities of E-commerce 67
services.

IT8761-SECURITY LAB Page 1


211718104001

IT8761-SECURITY LAB Page 2


Ex. No: 1(a) IMPLEMENTATION OF CAESAR CIPHER

AIM:
To write a Java program for implementing Caesar Cipher.
ALGORITHM:
Step 1: Start the program.
Step 2: Define a class Caesar Cipher.
Step 3: Declare a string ALPHABET.
Step 4: Define a function encrypt () to produce a cipher text and decrypt () to reproduce the
plain text.
Step 5: Define a main (), get the string and call encrypt () to encrypt the string and decrypt
() to reproduce the plain text and display it.
Step 6:Stop the program.

PROGRAM:
public 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);
}
public static void main(String[] args) throws java.lang.Exception
{
String msg = "Manoj Karthick";
System.out.println("Simulating Caesar Cipher\n------------------------");
System.out.println("Input : " + msg);
System.out.println("Encrypted Message : ");
System.out.println(caesarCipher.encode(msg, 3));
System.out.println("Decrypted Message : ");
System.out.println(caesarCipher.decode(caesarCipher.encode(msg, 3), 3));
}
}
OUTPUT:

RESULT:

Thus, java program to implement Caesar Cipher was written, executed and output is verified
successfully.
Ex. No: 1(b) IMPLEMENTATION OF PLAYFAIR CIPHER

AIM:
To write a Java program for implementing Playfair Cipher.

ALGORITHM:
Step 1: Start the program
Step 2: Define a class Basic to find the index of a char.
Step 3: Define a class PlayFair to define the key matrix, find the row position, column
position, encrypt the text and decrypt the text.
Step 4: Define a class PlayFairCipher, to get the plain text and then to encrypt and decrypt
the text.
Step 5: Display the encrypted text and decrypted text.
Step 6: Stop the program

PROGRAM:
import java.awt.Point;
public 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();
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 = "Naren Kishore"; /* 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));
}
}

OUTPUT:

RESULT:
Thus, java program to implement PlayFair Cipher was written, executed and output is
verified successful.
Ex. No: 1(c) IMPLEMENTATION OF HILL CIPHER

AIM:
To write a Java program for implementing Hill Cipher.

ALGORITHM:
Step 1: Start the program.
Step 2: Define a class HillCipher, in that declare 2 array one for key, other for inverse key
and define a string key.
Step 3: In this class, define a main(), get the choice to encrypt or decrypt.
Step 4: Based on the choice call encrypt() and decrypt() to find cipher and plain text.
Step 5: Display the result.
Step 6: Stop the program.

PROGRAM:
public class hillCipher
{
/* 3x3 key matrix for 3 characters at once */
public static int[][] keymat = new int[][] { { 1, 2, 1 }, { 2, 3, 2 },{ 2, 2, 1 } }; // key inverse matrix
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;
}
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 = ("Manoj Karthick");
System.out.println("simulation of Hill Cipher\n-------------------------");
System.out.println("Input message : " + msg);
msg = msg.toUpperCase();
msg = msg.replaceAll("\\s", "");
/* remove spaces */ n = msg.length() % 3;
/* append padding text X */
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);
}
}
OUTPUT:

RESULT:
Thus, java program to implement Hill Cipher was written, executed and output is verified
successfully.
Ex. No: 1(d) IMPLEMENTATION OF VIGENERE CIPHER

AIM:
To write a Java program for implementing Vigenere Cipher.

ALGORITHM:
Step 1: Start the program.
Step 2: Define a class VC1, in that define encipher() to produce a cipher text.
Step 3: Define decipher() to reproduce the plain text.
Step 4: Define a shift() to shift the values.
Step 5: In main(), define the text and key values and call the encipher() to encrypt and
decipher() to decrypt the encrypted text.
Step 6: Display the results.
Step 7: Stop the program.

PROGRAM:
public class VC1
{
public static String encipher(String s, String key)
{
StringBuilder builder = new
StringBuilder(); for(int i = 0; i < s.length(); i
++)
{
if(s.charAt(i) < 65 || s.charAt(i) > 90)
{ //ASCII character (capital letter)
throw new IllegalArgumentException("" +"Open text must contain
only capital letters");
}
//add shift modularly
char encyphered = s.charAt(i) + getShift(key, i) > 90 ? (char)((s.charAt(i) + getShift(key, i)) - 26) :
(char)(s.charAt(i) + getShift(key, i));
builder.append(encyphered);
}
return builder.toString();
}
public static String decipher(String s, String key)
{
StringBuilder builder = new StringBuilder();
for(int i = 0; i < s.length(); i ++)
{
if(s.charAt(i) < 65 || s.charAt(i) > 90)
{ //ASCII character (capital letter)
throw new IllegalArgumentException("" +"Ciphertext must contain
only capital letters");
}
//subtract shift modularly
char decyphered = s.charAt(i) - getShift(key, i) < 65 ? (char)((s.charAt(i) -
getShift(key, i)) + 26) : (char)(s.charAt(i) - getShift(key, i));
builder.append(decyphered);
}
return builder.toString();
}
private static int getShift(String key, int i)
{
if(key.charAt(i % key.length()) < 65 || key.charAt(i % key.length()) > 90)
{
throw new IllegalArgumentException("" +"Key phrase must contain only
capital letters");
}
return ((int)key.charAt(i % key.length())) - 65;
}
public static void main (String [] args)
{
String text = "MANOJKARTHICK";//only capital letters
String key = "MANO";
String enciphered = encipher(text, key);
System.out.println("IMPLEMENTATION OF VIGENERE CIPHER");
System.out.println("CIPHER TEXT IS:"+enciphered);
System.out.println("DECIPHERED TEXT IS:"+decipher(enciphered, key));
}
}

OUTPUT:

RESULT:
Thus, java program to implement Vigenere Cipher was written, executed and output is
verified successfully.
Ex. No: 2(a) IMPLEMENTATION OF RAIL FENCE –
ROW & COLUMN TRANSFORMATION

AIM:
To write a Java program for implementing Rail Fence – Row & Column Transformation.

ALGORITHM:
Step 1: Start the program
Step 2: Define a class railfencebasic, in that define Encryption() to produce cipher text.
Step 3: Define Decryption() to produce decipher text.
Step 4: Define a class railfencecipher, in that define main() and input the text to cipher and
decipher it.
Step 5: Display the result.
Step 6: Stop the program.

PROGRAM:
import java.util.*;
class RailFenceBasic
{
int depth;
String Encryption(String plainText,int depth)throws Exception
{
int r=depth,len=plainText.length();
int c=len/depth;
char mat[][]=new char[r][c];
int k=0;
String cipherText="";
for(int i=0;i< c;i++)
{
for(int j=0;j< r;j++)
{
if(k!=len)
mat[j][i]=plainText.charAt(k++);
else

mat[j][i]='X';
}
}
for(int i=0;i< r;i++)
{
for(int j=0;j< c;j++)
{
cipherText+=mat[i][j];
}
}
return cipherText;
}
String Decryption(String cipherText,int depth)throws Exception
{
int r=depth,len=cipherText.length();
int c=len/depth;
char mat[][]=new char[r][c];
int k=0;
String plainText="";
for(int i=0;i< r;i++)
{
for(int j=0;j< c;j++)
{
mat[i][j]=cipherText.charAt(k++);
}
}
for(int i=0;i< c;i++)
{
for(int j=0;j< r;j++)
{
plainText+=mat[j][i];
}
}
return plainText; }
}
class railfencecipher
{
public static void main(String args[])throws Exception
{
RailFenceBasic rf=new
RailFenceBasic(); Scanner scn=new
Scanner(System.in);
int depth;
String plainText,cipherText,decryptedText;
System.out.println("Enter plain text:");
plainText=scn.nextLine();
System.out.println("Enter depth for
Encryption:"); depth=scn.nextInt();
cipherText=rf.Encryption(plainText,depth);
System.out.println("Encrypted text is:\n"+cipherText);
decryptedText=rf.Decryption(cipherText, depth);
System.out.println("Decrypted text is:\n"+decryptedText);
}
}
OUTPUT:

RESULT:

Thus, java program to implement Vigenere Cipher was written, executed and output is
verified successfully.

.
Ex. No:3 IMPLEMENTATION OF DES

AIM:
To write a Java program for implementing DES.

ALGORITHM:
Step 1: Start the program
Step 2: Define a class DES, in that define a constructor to display the encrypted and
decrypted message.
Step 3: Define generateSymmetricKey(), to generate the key.
Step 4: Define encrypt() to encrypt the plain text.
Step 5: Define decrypt() to decrypt the ciphered
text. Step 6: Define main() to declare object for the
class. Step 7: Stop the program

PROGRAM:
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
public class Main
{
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 = "Manoj Karthick".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));
}
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();
}
}
}
OUTPUT:

RESULT:

Thus, DES was implemented using java and output is verified successfully.
Ex. No:4 IMPLMENTATION OF AES

AIM:
To implement AES using java.

ALGORITHM:
Step 1: Start the program.
Step 2: Define a class AES, in that assign values to plaintext, IV and key variables.
Step 3: Define main() to display the encrypted and decrypted text of plain text.
Step 4: Define encrypt() to generated cipher text and decrypt() to generate plain text.
Step 5: Stop the program.

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);
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 = "Mano";
String originalString = "Manoj Karthick";
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:
RESULT:

Thus, AES was implemented using java and output is verified successfully.
Ex. No: 5 IMPLEMENTATION OF RSA USING JAVASCRIPT AND HTML

AIM:
To write a program for implementing RSA using javascript and html.

ALGORITHM:
Step 1: Start the program
Step 2: Define a default constructor RSA to compare 2 prime numbers.
Step 3: Define a parameterized constructor to assign values.
Step 4: Define bytetostring() to convert byte to string.
Step 5: Define encrypt() to encrypt the text and decrypt() to reproduce the plain text.
Step 6: Define main() to call the encrypt() and decrypt() to perform respective operations
and display the results.
Step 7: Stop the program.

PROGRAM:
rsa.html
<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>
<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;
}
}
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>

OUTPUT:

RESULT:

Thus, java to implement RSA was written, executed and output is verified successfully.
Ex. No: 6 IMPLEMENTATION OF DIFFIE - HELLMAN

AIM:
To write a Java program for implementing Diffie - Hellman.

ALGORITHM:
Step 1: Start the program.
Step 2: Define class DiffeHellmanBigInt, in that main() get the details and pass the secret
key.
Step 3: Calculate the keys and display it.
Step 4: Stop the program.

PROGRAM:
import java.util.*;
import java.math.BigInteger;
public class DiffeHellmanBigInt
{
final static BigInteger one = new BigInteger("1");
public static void main(String args[])
{
Scanner stdin = new Scanner(System.in);
BigInteger p;
// Get a start spot to pick a prime from the user.
System.out.println("Enter the approximate value of p you want.");
String ans = stdin.next();
p = getNextPrime(ans);
System.out.println("Your prime is
"+p+".");
// Get the base for exponentiation from the user.
System.out.println("Now, enter a number in between 2 and p-1.");
BigInteger g = new BigInteger(stdin.next());
// Get A's secret number.
System.out.println("Person A: enter your secret number now.");
BigInteger a = new BigInteger(stdin.next());
// Make A's calculation.
BigInteger RESULTa = g.modPow(a,p);
// This is the value that will get sent from A to B.
// This value does NOT compromise the value of a easily.
System.out.println("Person A sends to person B "+RESULTa+".");
// Get B's secret number.
System.out.println("Person B: enter your secret number now.");
BigInteger b = new BigInteger(stdin.next());
// Make B's calculation.
BigInteger RESULTb = g.modPow(b,p);
// This is the value that will get sent from B to A.
// This value does NOT compromise the value of b easily.
System.out.println("Person B sends to person A "+RESULTb+".");
// Once A and B receive their values, they make their new calculations.
// This involved getting their new numbers and raising them to the
// same power as before, their secret number.
BigInteger KeyACalculates = RESULTb.modPow(a,p);
BigInteger KeyBCalculates = RESULTa.modPow(b,p);
// Print out the Key A calculates.
System.out.println("A takes "+RESULTb+" raises it to the power "+a+" mod "+p);
System.out.println("The Key A calculates is "+KeyACalculates+".");
// Print out the Key B calculates.
System.out.println("B takes "+RESULTa+" raises it to the power "+b+" mod "+p);
System.out.println("The Key B calculates is "+KeyBCalculates+".");
}
public static BigInteger getNextPrime(String ans)
{
BigInteger test = new BigInteger(ans);
while (!test.isProbablePrime(99))
test =
test.add(one); return test;
}
}
OUTPUT:

RESULT:
Thus, java program to implement Diffie Hellman was written, executed and output is
verified successfully.
Ex. No: 7 IMPLEMENTATION OF SHA-1

AIM:
To write a Java program for implementing SHA-1.

ALGORITHM:
Step 1: Start the program.
Step 2: Define a class HashTextTest, in that main() call sha1() to display secured hash
value.
Step 3: Define sha1(), in that define the instances and generate the hash value.
Step 4: Stop the program.

PROGRAM:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class HashTextTest
{
public static void main(String[] args) throws NoSuchAlgorithmException
{
System.out.println("Shared Hash Key Value is:"+sha1("Yuvashree Lakshmi"));
}
static String sha1(String input) throws NoSuchAlgorithmException
{
MessageDigest mDigest = MessageDigest.getInstance("SHA1");
byte[] result= mDigest.digest(input.getBytes());
StringBuffer sb = new
StringBuffer(); for (int i = 0; i
<result.length; i++)
{
sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
}

OUTPUT:

RESULT:
Thus, java program to implement SHA-1 was written, executed and output is verified
successfully.
Ex. No: 8 IMPLEMENTATION OF SIGNATURE SCHEME-
DIGITAL SIGNATURE STANDARD

AIM:
To implement Signature Scheme of Digital Signature Standard using java.

ALGORITHM:
Step 1: Start the program.
Step 2: Define a class DSS, in that define a main().
Step 3: Create instance for KeypairGenerator
class. Step 4: Generate Key Pair using KeyPair
Class.
Step 5: Send the data to encrypt and sign.
Step 6: Sign the data using Signature class.
Step 7: Display the signature and verification status.
Step 8: Stop the program.

PROGRAM:
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Signature;
import sun.misc.BASE64Encoder;
public class DSS
{
public static void main(String[] args) throws Exception
{
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair keyPair = kpg.genKeyPair();
byte[] data =
"test".getBytes("UTF8");
Signature sig = Signature.getInstance("MD5WithRSA");
sig.initSign(keyPair.getPrivate());
sig.update(data);
byte[] signatureBytes = sig.sign();
System.out.println("Signature:" + new BASE64Encoder().encode(signatureBytes));
sig.initVerify(keyPair.getPublic());
sig.update(data);
System.out.println(sig.verify(signatureBytes));
}
}

OUTPUT:

RESULT:
Thus, java program to implement Signature Scheme of Digital Signature Standard was
written, executed and output is verified successfully.
Ex. No: 9 DEMONSTRATE INTRUSION DETECTION SYSTEM (IDS) USING SNORT

AIM:
To demonstrate intrusion detection system (ids) using snort.

PROCEDURE:
SNORT can be configured to run in three modes:
1. Sniffer mode
2. Packet Logger mode
3. Network Intrusion Detection System mode

Sniffer modesnort –v Print out the TCP/IP packets header on the screen
Snort –vd show the TCP/IP ICMP header with application data in transit.

Packet Logger modesnort –dev –l c:\log [create this directory in the C drive] and snort will
automatically know to go into packet logger mode, it collects every packet it sees and places it in
log directory. snort –dev –l c:\log –h ipaddress/24 This rule tells snort that you want to print out the
data link and TCP/IP headers as well as application data into the log directory. snort –l c:\log –b
This is binary mode logs everything into a single file.

Network Intrusion Detection System modesnort –d c:\log –h ipaddress/24 –c snort.conf - This


is a configuration file applies rule to each packet to decide it an action based upon the rule type in
the file. Snort –d –h ipaddress/24 –l c:\log –c snort.conf - This will configure snort to run in its most
basic NIDS form, logging packets that trigger rules specifies in the snort.conf.

Step 1: Download SNORT from snort.org


Step 2: Install snort with or without database support.
Step 3: Select all the components and Click Next.
Step 4: Install and Close.
Step 5: Skip the WinPcap driver installation
Step 6; Add the path variable in windows environment variable by selecting new classpath.
Step 7: Create a path variable and point it at snort.exe variable name path and variable
value c:\snort\bin.
Step 8: Click OK button and then close all dialog boxes.
Step 9: Open command prompt and type the following commands:

C:\Snort\bin>Snort - v
C:\Snort\bin>Snort – vd
RESULT:
Thus, Intrusion Detection System was demonstrated using Snort tool successfully.
Ex. No: 10 Automated Attack and Penetration Tools
Exploring N-Stalker, a Vulnerability Assessment Tool

AIM:
To demonstrate intrusion detection system (ids) using snort.
PROCEDURE:

To initiate the installation of N-Stalker Web Application Security Scanner, follow the procedures
below:

Double click on N-Stalker Web Application Security Scanner installation package downloaded as
1. per instructions of the previous section;

2. Select the preferred language to initiate the installation;

3. Click "Next" to continue


4. Accept the license agreement by pressing “I Agree” button;

5. Choose appropriate components (default option is a safe choice) and click “Next” button;
6. Choose destination folder and click “Next” button;

7. N-Stalker Web Application Security Scanner will be installed on the desired folder;
To initiate the application, you should either search for N-Stalker icon in your desktop or "N-
8. Stalker Web Application Security Scanner" group in your start menu.

Use the URLs collected

The manual test is initiated by means of navigation through the application’s URLs with the
Browser activated by N-Stalker’s internal Proxy which captures all requisitions and responses from
the application (as in the configuration for recording of a navigation macro). Once the URLs you
wish to analyse are captured, we can inform on how to use them for analysis, selecting and
redirecting the attack mode.

The first stage is to know the application’s URL and the path you wish it to follow, and then
choose the "Manual Test" policy to initiate the manual Scan manual, according to the steps
1. below:

Type the URL of the web application and in "Choose Scan Policy", it is necessary to choose the
2. "Manual Test” policy (crawl through the URL and standby for manual attack)".
After finishing, please click on the "Next" button to proceed until reaching the "Review
Summary" screen. If all is correct, press the "Start Session" button. The "Scanning Assistant" is
closed and the "Scanning Interface Scanning" is open to initiate the manual analysis section.

4. In "Scan Options" click on the "Start Proxy" button. The Proxy will be iniatited.

The Proxy options are available as an additional panel with the name "Proxy Panel", on the
screen’s lower corner. Just click on the "Start Proxy" button:

After initiating, click on the "Start Browser" button. The N-Stalker will try to automatically
configure your navigator for use inside the “Macro Recorder” tool. If you find problems doing so,
6. Please, configure it manually (using the network connection of your browser).
Start navigating throughout your application. Run through a path you would like the N-Stalker
Spider engine would also follow. N-Stalker records all information within the "Proxy Panel"
7. Table:

8. As soon as navigation is completed by the application , click on the "Stop Proxy" button.

The “Website Tree” control allows user to visualize all the resources that were gathered during the
trip of the N-Stalker spider/proxy engine, including web pages and transactions. The “Website
Tree” is co-ordinated by web servers (URLs) which represent all the various hosts located on the
crawler path (please remember that only the URL itself and the allowed hosts can be crawled
through).

Authorizing a rejected host

Sometimes the applications may refer to external web sites which are not relevant for the
verification of global security, however, there are some situations where external web sites are part
of the inspected application and thus must be assessed.

In the "Scanner Events" tree, on the "Rejected Hosts" option, it is possible to see a list of web sites
that had been rejected by the N-Stalker spider engine due to configuration restrictions.
7. In case you need to explicitly authorize a host from the list, please right click on it, then click
on "Enable Host" and confirm by clicking on the "Yes" button.

8. After navigating throughout your application and having accomplished the


desired configurations, click on the "Start Scan" button to initiate the scanning
engine.

Then a screen with 3 options related to the data stored by the proxy is displayed. Please select the
option of your choice in case you wish to initiate Scan only with data stored by the proxy. Use
the proxy data to track new URLs or to track all the URLs again including data stored by the
proxy.

Details:

• Use proxy data only and do not crawl for additional URLs
If you select this option the Scanner will be executed only in the URLs stored by the proxy.
• Use proxy data and crawl for new URLs additionally
If you select this option the Scanner will be executed in the URLs stored by the proxy but will
also search for new URLs to be analysed.

• Crawl all URLs again including those from proxy data


If you select this option the Spider will track all URLs again, including the URLs stored
beforehand by the proxy.

On the right corner of the screen, the quantity of URLs captured by the proxy at the time of
navigation is then informed. Please select your option and click on the "Done" button to initiate
execution of tests.

The "Scanning Session Interface" is open for execution of tests.

On the "Scan Modules" guide, on the footer of the N-Stalker scanning interface, there is a series of
guides containing technical information about the scanning progress status including event items,
components and depuration.

Before starting the manual test wait until the status shifts to the "Standby Mode - You may now run
manual attacks or press "Close" to finish session" on the footer of the application.
RESULT:
Thus, Automated Attack and Penetration Tools was demonstrated using Snort tool
successfully.
Ex. No: 11 INSTALLATION OF ROOTKITS AND
STUDY ABOUT THE VARIETY OF OPTIONS

AIM:
To install rootkits and study about the variety of options.

PROCEDURE:
A rootkit is a particularly nasty piece of malware that doesn’t behave like your typical virus.
Rootkits insert themselves into the very heart of the operating system; usually at or below the
kernel level. This makes them extremely difficult to detect and sometimes impossible to remove.
Specific antivirus programs specialize in the detection and removal of rootkits. Below we list the
five best anti-rootkit program.
Rkhunter is software that finds rootkits on a Linux server. Rootkits are installed by hackers so that
they can always access the server. In this doc, you'll be able to see how you can prevent rootkits
using rkhunter on Ubuntu.
Step 1: Installing prerequisites
We need to install a number of prerequisites to properly use rkhunter:
apt-get install binutils libreadline5 libruby ruby ruby ssl-cert unhide.rb mailutils
Once the install finishes, you can proceed to the next step.
Step 2: Installing rkhunter
We'll download rkhunter by using wget. If wget hasn't been installed on your system yet,
execute: apt-get install wget
Now download rkhunter:
wget http://downloads.sourceforge.net/project/rkhunter/rkhunter/1.4.2/rkhunter-1.4.2.tar.gz
Untar the download:
tar xzvf rkhunter*
Navigate to the rkhunter
directory: cd rkhunter*
Install rkhunter:
./installer.sh --layout /usr --install
The installation output should be similar to this:
Checking system for:
Rootkit Hunter installer files: found
A web file download command: wget
found Starting installation:
Checking installation directory "/usr": it exists and is writable.
Checking installation directories:
Directory /usr/share/doc/rkhunter-1.4.2: creating: OK
Directory /usr/share/man/man8: exists and is
writable. Directory /etc: exists and is writable.
Directory /usr/bin: exists and is writable.
Directory /usr/lib: exists and is writable.
Directory /var/lib: exists and is writable.
Directory /usr/lib/rkhunter/scripts: creating: OK
Directory /var/lib/rkhunter/db: creating: OK
Directory /var/lib/rkhunter/tmp: creating: OK
Directory /var/lib/rkhunter/db/i18n: creating:
OK
Directory /var/lib/rkhunter/db/signatures: creating: OK
Installing check_modules.pl: OK
Installing filehashsha.pl: OK
Installing stat.pl: OK
Installing readlink.sh: OK
Installing backdoorports.dat: OK
Installing mirrors.dat: OK
Installing program: s_bad.dat: OK
Installing suspscan.dat: OK
Installing rkhunter.8: OK
Installing ACKNOWLEDGMENTS: OK
Installing CHANGELOG: OK
Installing FAQ: OK
Installing LICENSE: OK
Installing README: OK
Installing language support files: OK
Installing ClamAV signatures: OK
Installing rkhunter: OK
Installing rkhunter.conf: OK
Installation complete
Step 3: Using rkhunter
Data files keep information about possible threats.
Regularly updating your data files is necessary for an up-to-date system. You can update them
using the rkhunter command:
rkhunter --update
This will OUTPUT a list with data files that were updated and those that weren't updated:
[ Rootkit Hunter version 1.4.2 ]
Checking rkhunter data files...
Checking file mirrors.dat [ No update ]
Checking file program: s_bad.dat [ Updated ]
Checking file backdoorports.dat [ No update ]
Checking file suspscan.dat [ No update ]
Checking file i18n/cn [ No update ]
Checking file i18n/de [ No update ]
Checking file i18n/en [ No update ]
Checking file i18n/tr [ No update ]
Checking file i18n/tr.utf8 [ No update ]
Checking file i18n/zh [ No update ]
Checking file i18n/zh.utf8 [ No update ]
We are now ready to perform our first test. The test will look for known rootkits and generic
security issues (such as root access over SSH) and log its findings. You will manually need to press
"Enter" to continue after checks.
After the test, we can see errors and warnings:
cat /var/log/rkhunter.log
Step 4: Enabling email notifications
Rkhunter can be configured to send an email when a threat is found. To configure this feature, start
by opening the rkhunter.conf file:
vi /etc/rkhunter.conf
Search for MAIL-ON-WARNING, then add an email address.
You can optionally scroll through the configuration for more options, however, by default, it should
work fine. You can check your configuration file:
rkhunter -C
If there's no output, your configuration file is valid.

RESULT:
Thus, Rootkit was installed and various options were studied successfully.
CONTENT BEYOND SYLLABUS
Ex: No:12 PRETTY GOOD PRIVACY [CONTENT BEYOND THE SYLLABUS]

AIM:

To write a java program to implement pretty good privacy.

DESCRIPTION:

 PGP stands for Pretty Good Privacy (PGP) which is invented by Phil Zimmermann.

 PGP (Pretty Good Privacy), is a popular program that is used to provide


confidentiality and authentication services for electronic mail and file storage.

 The following are the services offered by PGP:

1. Authentication
2. Confidentiality
3. Compression
4. Email Compatibility
5. Segmentation

 PGP uses a digital signature (a combination of hashing and public key encryption) to
provide integrity, authentication, and non-repudiation. PGP uses a combination of secret key
encryption and public key encryption to provide privacy. Therefore, we can say that the
digital signature uses one hash function, one secret key, and two private-public key pairs.

 PGP is an open source and freely available software package for email security.

 PGP provides authentication through the use of Digital Signature.

 It provides confidentiality through the use of symmetric block encryption.

 It provides compression by using the ZIP algorithm, and EMAIL compatibility using the
radix-64 encoding scheme.
OUTPUT:

GENERATION OF KEYS:

PGP ENCRYPTION:
PGP DECRYPTION:

RESULT:
Thus, the pretty good privacy has been implemented successfully.
Ex. No : 13
TRIPLE DES
Date :

AIM:
To implement the TRIPLE DES in java.
ALGORITHM:
1. Start the program.
2. Encrypt the plaintext blocks using single DES with key K1.
3. Now decrypt the output of step 1 using single DES with key K2.
4. Finally, encrypt the output of step 2 using single DES with key K3.
5. The output of step 3 is the ciphertext.
6. Decryption of a ciphertext is a reverse process. User first decrypt using K3, then encrypt with K2, and
finally decrypt with K1.
7. Stop the program.

PROGRAM:
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class TripleDESTest
{
public static void main(String[] args) throws Exception
{
String text = "textToEncrypt";
String codedtext = new TripleDESTest()._encrypt(text,"SecretKey");
String decodedtext = new TripleDESTest()._decrypt(codedtext,"SecretKey");
System.out.println(codedtext + " ---> " + decodedtext);
}
private String _encrypt(String message, String secretKey) throws Exception
{
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] digestOfPassword = md.digest(secretKey.getBytes("utf-8"));
byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
SecretKey key = new SecretKeySpec(keyBytes, "DESede"); Cipher cipher =
Cipher.getInstance("DESede"); cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plainTextBytes = message.getBytes("utf-8");
byte[] buf = cipher.doFinal(plainTextBytes);
byte [] base64Bytes = Base64.encodeBase64(buf);
String base64EncryptedString = new String(base64Bytes);
return base64EncryptedString;
}
private String _decrypt(String encryptedText, String secretKey) throws Exception {
byte[] message = Base64.decodeBase64(encryptedText.getBytes("utf-8")); MessageDigest md =
MessageDigest.getInstance("SHA-1");
byte[] digestOfPassword = md.digest(secretKey.getBytes("utf-8")); byte[] keyBytes =
Arrays.copyOf(digestOfPassword, 24); SecretKey key = new SecretKeySpec(keyBytes, "DESede");
Cipher decipher = Cipher.getInstance("DESede");
decipher.init(Cipher.DECRYPT_MODE, key);
byte[] plainText = decipher.doFinal(message);
return new String(plainText, "UTF-8");
}
}
OUTPUT:

RESULT:
Thus the program to implement the TRIPLE DES in java has been executed and the output was verified
successfully.
Ex. No : 14
Analysis the Security Vulnerabilities of E-commerce services.
Date :

Learning Objectives
After going through this session, you should be able to:
 Know about Security Vulnerabilities of E-commerce services.
 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
Software life cycle not secure.
Over the years, efforts to enhance software development life cycle (SDLC) practices have been shown to
improve software quality, reliability, and fault-tolerance. Now-a-days strategies to improve the security of
software in organizations such as Microsoft, Oracle, and Motorola have resulted in software products
with less vulnerabilities and greater dependability, trustworthiness, and robustness.
As per the SANS Institute’s Top 20 list of security vulnerabilities, theMITRE Common Vulnerabilities
and Exposures (CVE) site, the US-CERT
Technical Cyber Security Alerts site, and the Microsoft Security Advisory site show that common
software defects are the leading cause of security vulnerabilities (buffer overflows have been the most
common software defect leading to security vulnerabilities).
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.
Vulnerabilities due to input validations
Buffer Overflow: A buffer overflow condition occurs when a program attempts to copy more data in a
buffer than it can hold. Buffer overflow is probably the best-known form of software security
vulnerability. At the code
level, buffer overflow vulnerabilities usually involve the violation of a programmer's assumptions.
Hackers use buffer overflows to corrupt the execution stack of a web application. Buffer overflow flaws
can be present in both the web server or application server products that serve the static and dynamic
aspects of the site. Buffer overflows generally resulted in to crashes. Other type of attacks will create the
situation like lack of availability are possible, including putting the program into an infinite loop.
Log Forging: Writing invalidated user input to log files can give access to attacker for forging log entries
or injecting malicious content into the logs. Log forging vulnerabilities occur in following conditions:
i) Data copied to an application from an unreliable source.
ii) The data is copied to an application or system log file.
Applications uses log file to store a history of events for later review and record, statistics gathering, or
debugging. Analysis of the log files may be misdirected if an attacker can supply inappropriate data to the
application. In the most common case, an attacker may be able to insert false entries into the log file by
providing the application with input that includes appropriate characters. If the log file is processed
automatically, the attacker can render the file unusable by corrupting the format of the file or injecting
unexpected characters. A more dangerous attack might involve changing the log file statistics.
Missing XML Validation: Failure to implement validation when parsing XML gives an attacker the way
to supply malicious input. By accepting an XML document without validating it against a DTD or XML
schema, the programme gives chance to attackers to copy unexpected, unreasonable, or malicious input. It
is not possible for an XML parser to validate all aspects of a document's content; a parser cannot
understand the complete semantics of the data. However, a parser can do a complete and thorough job of
checking the document's structure and therefore guarantee to the code that processes the document that
the content is well-formed.
Validation checks in client: Performing validation check in client side code, mostly JavaScript, provides
no protection for server-side code.
An attacker can simply disable JavaScript, use telnet, or use a security testing proxy to bypass the client
side validation. Client-side validation is widely used, but is not security relevant.
Vulnerabilities in database servers: There are various techniques to attack a database. External attacks
may exploit configuration weaknesses that expose the database server. Also weak and insecure Web
application can be used to exploit the database. An application with excess privilege in the database can
put database at risk. The main threats to a database server are:
SQL injection: Technique used to attack database through website entry fields.
Network eavesdropping: It is a network level attack consisting of capturing packets from the networked
computers.
Unauthorized server access: Attacked made unauthorised access through various loopholes in the
system such as O/S, non availability of firewall etc.
Password cracking: Technique of recovering password from data stored in computer.
REFERENCES

 WikiPedia
o https://en.wikipedia.org/wiki/GMER
o https://en.wikipedia.org/wiki/Snort_(software)
o https://en.wikipedia.org/wiki/Trojan_horse_(computing)

 GeeksForGeeks
o https://www.geeksforgeeks.org/rsa-algorithm-cryptography/
o https://www.geeksforgeeks.org/sha-1-hash-in-java/
o https://www.geeksforgeeks.org/caesar-cipher-in-cryptography/
o https://www.geeksforgeeks.org/how-to-solve-rsa-algorithm-problems/
o https://www.geeksforgeeks.org/playfair-cipher-with-examples/

 Build Your Own Security Lab, Michael Gregg, Wiley India


o https://doc.lagout.org/security/Build%20Your%20Own%20Security%20Lab%20for
%20Network%20Testing.pdf

 Some other Websites


o https://forums.malwarebytes.com/topic/200301-sneaky-rootkit-help-needed/
o https://itstillworks.com/use-gmer-remove-rootkit-6102694.html

You might also like