You are on page 1of 80

EX NO:1(A) CAESAR CIPHER

AIM:
To implement the Caesar cipher in java.
ALGORITHM:
Caesar cipher (shift cipher) is a simple substitution cipher based on a replacement of every
single character of the open text with a character, which is fixed number of positions further down the
alphabet.
In the times of Julius Caesar was used only the shift of 3 characters, but nowadays the
term Caesar cipher refers to all variants (shifts) of this cryptosystem.
The encryption can be described with the following formula:

Ci - i-th character of the closed text


Ti - i-th character of the open text
k - shift
m - length of the alphabet
The process of decryption uses reverted procedure:

1
PROGRAM :
importjava.util.Scanner;

public class ceasercipher


{
public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";

public static String encrypt(String plainText, intshiftKey)


{
plainText = plainText.toLowerCase();
String cipherText = "";
for (inti = 0; i<plainText.length(); i++)
{
intcharPosition = ALPHABET.indexOf(plainText.charAt(i));
/*manual prepared by www.gr-solution.blogspot.com*/
intkeyVal = (shiftKey + charPosition) % 26;
charreplaceVal = ALPHABET.charAt(keyVal);
cipherText += replaceVal;
}
returncipherText;
}

public static String decrypt(String cipherText, intshiftKey)


{
cipherText = cipherText.toLowerCase();
String plainText = "";
for (inti = 0; i<cipherText.length(); i++)
{
intcharPosition = ALPHABET.indexOf(cipherText.charAt(i));
intkeyVal = (charPosition - shiftKey) % 26;
if (keyVal< 0)
{
keyVal = ALPHABET.length() + keyVal;
}
charreplaceVal = ALPHABET.charAt(keyVal);
plainText += replaceVal;
}
returnplainText;
}

public static void main(String[] args)


{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String for Encryption: ");
String message = new String();
/*manual prepared by www.gr-solution.blogspot.com*/
message = sc.next();
System.out.println("Encryption message= "+encrypt(message, 3));
System.out.println("Decryption message= "+decrypt(encrypt(message, 3), 3));
sc.close();
}
}

2
OUTPUT:

RESULT:
Thus the program to implement the Caesar cipher in java has been executed and the output was
verified successfully.

3
EX NO: 1(B) PlAYFAIR CIPHER

AIM:

To implement a playfair cipher in java.

ALGORITHM:

Start the program.


Declare the class and required variables.
Implement the playfair cipher procedure
Access the member functions using the objects.
Stop the program.

4
PROGRAM :
importjava.util.Scanner;

public class PlayfairCipherEncryption


{
private String KeyWord = new String();
private String Key = new String();
private char matrix_arr[][] = new char[5][5];

public void setKey(String k)


{
String K_adjust = new String();
boolean flag = false;
K_adjust = K_adjust + k.charAt(0);
for (inti = 1; i<k.length(); i++)
{
for (int j = 0; j <K_adjust.length(); j++)
{
if (k.charAt(i) == K_adjust.charAt(j))
{
flag = true;
}
}
if (flag == false)
K_adjust = K_adjust + k.charAt(i);
flag = false;
}
KeyWord = K_adjust;
}
/*manual prepared by www.gr-solution.blogspot.com*/
public void KeyGen()
{
boolean flag = true;
char current;
Key = KeyWord;
for (inti = 0; i< 26; i++)
{
current = (char) (i + 97);
if (current == 'j')
continue;
for (int j = 0; j <KeyWord.length(); j++)
{
if (current == KeyWord.charAt(j))
{
flag = false;
break;
}
}
if (flag)
Key = Key + current;
flag = true;
}

5
System.out.println(Key);
matrix();
}
/*manual prepared by www.gr-solution.blogspot.com*/
private void matrix()
{
int counter = 0;
for (inti = 0; i< 5; i++)
{
for (int j = 0; j < 5; j++)
{
matrix_arr[i][j] = Key.charAt(counter);
System.out.print(matrix_arr[i][j] + " ");
counter++;
}
System.out.println();
}
}

private String format(String old_text)


{
inti = 0;
intlen = 0;
String text = new String();
len = old_text.length();
for (inttmp = 0; tmp<len; tmp++)
{
if (old_text.charAt(tmp) == 'j')
{
text = text + 'i';
}
else
text = text + old_text.charAt(tmp);
}
len = text.length();
for (i = 0; i<len; i = i + 2)
{
if (text.charAt(i + 1) == text.charAt(i))
{
text = text.substring(0, i + 1) + 'x' + text.substring(i + 1);
}
}
return text;
}

private String[] Divid2Pairs(String new_string)


{
String Original = format(new_string);
int size = Original.length();
if (size % 2 != 0)
{
size++;
Original = Original + 'x';
}
String x[] = new String[size / 2];

6
int counter = 0;
for (inti = 0; i< size / 2; i++)
{
x[i] = Original.substring(counter, counter + 2);
counter = counter + 2;
}
return x;
}

publicint[] GetDiminsions(char letter)


{
int[] key = new int[2];
if (letter == 'j')
letter = 'i';
for (inti = 0; i< 5; i++)
{
for (int j = 0; j < 5; j++)
{
if (matrix_arr[i][j] == letter)
{
key[0] = i;
key[1] = j;
break;
}
}
}
return key;
}

public String encryptMessage(String Source)


{
String src_arr[] = Divid2Pairs(Source);
String Code = new String();
char one;
char two;
int part1[] = new int[2];
int part2[] = new int[2];
for (inti = 0; i<src_arr.length; i++)
{
one = src_arr[i].charAt(0);
two = src_arr[i].charAt(1);
part1 = GetDiminsions(one);
part2 = GetDiminsions(two);
if (part1[0] == part2[0])
{
if (part1[1] < 4)
part1[1]++;
else
part1[1] = 0;
if (part2[1] < 4)
part2[1]++;
else
part2[1] = 0;
}
else if (part1[1] == part2[1])

7
{
if (part1[0] < 4)
part1[0]++;
else
part1[0] = 0;
if (part2[0] < 4)
part2[0]++;
else
part2[0] = 0;
}
else
{
int temp = part1[1];
part1[1] = part2[1];
part2[1] = temp;
}
Code = Code + matrix_arr[part1[0]][part1[1]]
+ matrix_arr[part2[0]][part2[1]];
}
return Code;
}

public static void main(String[] args)


{
PlayfairCipherEncryption x = new PlayfairCipherEncryption();
Scanner sc = new Scanner(System.in);
System.out.println("Enter a keyword:");
String keyword = sc.next();
x.setKey(keyword);
x.KeyGen();
System.out
.println("Enter word to encrypt: (Make sure length of message is even)");
String key_input = sc.next();
if (key_input.length() % 2 == 0)
{
System.out.println("Encryption: " + x.encryptMessage(key_input));
}
else
{
System.out.println("Message length should be even");
}
sc.close();
}
}

8
OUTPUT:

RESULT:
Thus the program to implement the Playfair cipher in java has been executed and the output was
verified successfully.

9
EX NO: 1(c) HILL CIPHER

AIM:

To implement the HILL CIPHER in java

ALGORITHM:

Start the program.


Declare the class and required variables.
Implement the Hill cipher in java
Create the object for the class in the main program.
Access the member functions using the objects.
Stop the program.

10
PROGRAM :

importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStreamReader;

public class HillCipher


{
intkeymatrix[][];
intlinematrix[];
intresultmatrix[];

public void divide(String temp, int s)


{
while (temp.length() > s)
{
String sub = temp.substring(0, s);
temp = temp.substring(s, temp.length());
perform(sub);
}
if (temp.length() == s)
perform(temp);
else if (temp.length() < s)
{
for (inti = temp.length(); i< s; i++)
temp = temp + 'x';
perform(temp);
}
}

public void perform(String line)


{
linetomatrix(line);
linemultiplykey(line.length());
result(line.length());
}

public void keytomatrix(String key, intlen)


{
keymatrix = new int[len][len];
int c = 0;
for (inti = 0; i<len; i++)
{
for (int j = 0; j <len; j++)
{
keymatrix[i][j] = ((int) key.charAt(c)) - 97;
c++;
}
}
}

public void linetomatrix(String line)


{
linematrix = new int[line.length()];
for (inti = 0; i<line.length(); i++)

11
{
linematrix[i] = ((int) line.charAt(i)) - 97;
}
}

public void linemultiplykey(intlen)


{
resultmatrix = new int[len];
for (inti = 0; i<len; i++)
{
for (int j = 0; j <len; j++)
{
resultmatrix[i] += keymatrix[i][j] * linematrix[j];
}
resultmatrix[i] %= 26;
}
}

public void result(intlen)


{
String result = "";
for (inti = 0; i<len; i++)
{
result += (char) (resultmatrix[i] + 97);
}
System.out.print(result);
}
/*manual prepared by www.gr-solution.blogspot.com*/
publicboolean check(String key, intlen)
{
keytomatrix(key, len);
int d = determinant(keymatrix, len);
d = d % 26;
if (d == 0)
{
System.out
.println("Invalid key!!! Key is not invertible because determinant=0...");
return false;
}
else if (d % 2 == 0 || d % 13 == 0)
{
System.out
.println("Invalid key!!! Key is not invertible because determinant has common factor with
26...");
return false;
}
else
{
return true;
}
}
/*manual prepared by www.gr-solution.blogspot.com*/
publicint determinant(int A[][], int N)
{
int res;

12
if (N == 1)
res = A[0][0];
else if (N == 2)
{
res = A[0][0] * A[1][1] - A[1][0] * A[0][1];
}
else
{
res = 0;
for (int j1 = 0; j1 < N; j1++)
{
int m[][] = new int[N - 1][N - 1];
for (inti = 1; i< N; i++)
{
int j2 = 0;
for (int j = 0; j < N; j++)
{
if (j == j1)
continue;
m[i - 1][j2] = A[i][j];
j2++;
}
}
res += Math.pow(-1.0, 1.0 + j1 + 1.0) * A[0][j1]
* determinant(m, N - 1);
}
}
return res;
}

public void cofact(intnum[][], int f)


{
int b[][], fac[][];
b = new int[f][f];
fac = new int[f][f];
int p, q, m, n, i, j;
for (q = 0; q < f; q++)
{
for (p = 0; p < f; p++)
{
m = 0;
n = 0;
for (i = 0; i< f; i++)
{
for (j = 0; j < f; j++)
{
b[i][j] = 0;
if (i != q && j != p)
{
b[m][n] = num[i][j];
if (n < (f - 2))
n++;
else
{
n = 0;

13
m++;
}
}
}
}
fac[q][p] = (int) Math.pow(-1, q + p) * determinant(b, f - 1);
}
}
trans(fac, f);
}

void trans(intfac[][], int r)


{
inti, j;
int b[][], inv[][];
b = new int[r][r];
inv = new int[r][r];
int d = determinant(keymatrix, r);
int mi = mi(d % 26);
mi %= 26;
if (mi < 0)
mi += 26;
for (i = 0; i< r; i++)
{
for (j = 0; j < r; j++)
{
b[i][j] = fac[j][i];
}
}
for (i = 0; i< r; i++)
{
for (j = 0; j < r; j++)
{
inv[i][j] = b[i][j] % 26;
if (inv[i][j] < 0)
inv[i][j] += 26;
inv[i][j] *= mi;
inv[i][j] %= 26;
}
}
System.out.println("\nInverse key:");
matrixtoinvkey(inv, r);
}
/*manual prepared by www.gr-solution.blogspot.com*/

publicint mi(int d)
{
int q, r1, r2, r, t1, t2, t;
r1 = 26;
r2 = d;
t1 = 0;
t2 = 1;
while (r1 != 1 && r2 != 0)
{
q = r1 / r2;

14
r = r1 % r2;
t = t1 - (t2 * q);
r1 = r2;
r2 = r;
t1 = t2;
t2 = t;
}
return (t1 + t2);
}

public void matrixtoinvkey(intinv[][], int n)


{
String invkey = "";
for (inti = 0; i< n; i++)
{
for (int j = 0; j < n; j++)
{
invkey += (char) (inv[i][j] + 97);
}
}
System.out.print(invkey);
}

public static void main(String args[]) throws IOException


{
HillCipherobj = new HillCipher();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int choice;
System.out.println("Menu:\n1: Encryption\n2: Decryption");
choice = Integer.parseInt(in.readLine());
System.out.println("Enter the line: ");
String line = in.readLine();
System.out.println("Enter the key: ");
String key = in.readLine();
doublesq = Math.sqrt(key.length());
if (sq != (long) sq)
System.out
.println("Invalid key length!!! Does not form a square matrix...");
else
{
int s = (int) sq;
if (obj.check(key, s))
{
System.out.println("Result:");
obj.divide(line, s);
obj.cofact(obj.keymatrix, s);
}
}
}
}

15
OUTPUT:

RESULT:
Thus the program to implement the HILL cipher in java has been executed and the output was
verified successfully.

16
EX NO:1(d) VIGENERE CIPHER

AIM:

To implement the vigenere cipher in java.

ALGORITHM:

Start the program.


Declare the class and required variables.
Declare the constructor and destructor of the class.
Implement the vigenere cipher in java
Access the member functions using the objects.
Stop the program.

17
PROGRAM:

public class VigenereCipher


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

public static String decrypt(String text, final String key)


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

public static void main(String[] args)


{
String key = "VIGENERECIPHER";
String message = "welcome to vigener cipher";
String encryptedMsg = encrypt(message, key);
System.out.println("String: " + message);
System.out.println("Encrypted message: " + encryptedMsg);
System.out.println("Decrypted message: " + decrypt(encryptedMsg, key));
}
}

18
OUTPUT:

RESULT:
Thus the program to implement the vigenere cipher in java has been executed and the output was
verified successfully.

19
EX NO: 1(e) Rail fence row & Column Transformation

AIM:

To implement the Rail fence row & Column Transformation in java

ALGORITHM:

Start the program.


Declare the class and required variables.
Declare the constructor and destructor of the class.
Implement the Rail fence row & Column Transformation
Access the member functions using the objects.
Stop the program.

20
PROGRAM:

import java.io.*;
importjava.awt.*;
importjavax.swing.*;
importjava.awt.event.*;

//RailFence Technique Done using Swings


classrailfence extends JFrame implements ActionListener
{
JTextField t1,t2;
JButton b1;
JLabel l1,l2;
Container c;
railfence()
{ c=getContentPane();
c.setLayout(new GridLayout(3,2,2,3));

t1=new JTextField(10);
t2=new JTextField(10);

l1=new JLabel("Enter Your Message to Encrypt:");


l2=new JLabel("Encrypted Text:");
/*manual prepared by www.gr-solution.blogspot.com*/
t2.setEditable(false);
b1=new JButton("Submit");
b1.addActionListener(this);
c.add(l1); c.add(t1);
c.add(l2); c.add(t2);
c.add(b1);

setTitle("RailFence Technique");
setVisible(true);
pack();
}

public void actionPerformed(ActionEventae)


{
encrypt();
}

void encrypt()
{
String s=t1.getText();
intlen=s.length();

String s1="";
String s2="";
for(inti=0;i<len;i=i+2)
{
s1=s1+""+s.charAt(i);

}
for(int j=1;j<len;j=j+2)
{

21
s2=s2+""+s.charAt(j);
}
s1=s1+s2;
t2.setText(s1);
}
/*manual prepared by www.gr-solution.blogspot.com*/
public static void main(String args[])
{
newrailfence();
}
}

22
OUTPUT:

RESULT:
Thus the program to implement the Rail fence row & Column Transformation in java has been
executed and the output was verified successfully.

23
EX NO:2(a) DES

AIM:

To implement the DES in java

ALGORITHM:

Start the program.


Declare the class and required variables.
Declare the constructor and destructor of the class.
Implement the DES in java
Access the member functions using the objects.
Stop the program.

24
PROGRAM:
importjavax.swing.*;
importjava.security.SecureRandom;
importjavax.crypto.Cipher;
importjavax.crypto.KeyGenerator;
importjavax.crypto.SecretKey;
importjavax.crypto.spec.SecretKeySpec;
importjava.util.Random ;
class DES {
byte[] skey = new byte[1000];
String skeyString;
static byte[] raw;
String inputMessage,encryptedData,decryptedMessage;

public DES() {
try {
generateSymmetricKey();

inputMessage=JOptionPane.showInputDialog(null,"Enter message to encrypt");


byte[] ibyte = inputMessage.getBytes();
byte[] ebyte=encrypt(raw, ibyte);
String encryptedData = new String(ebyte);
System.out.println("Encrypted message "+encryptedData);
JOptionPane.showMessageDialog(null,"Encrypted Data "+"\n"+encryptedData);

byte[] dbyte= decrypt(raw,ebyte);


String decryptedMessage = new String(dbyte);
System.out.println("Decrypted message "+decryptedMessage);

JOptionPane.showMessageDialog(null,"Decrypted Data "+"\n"+decryptedMessage);


}
catch(Exception e) {
System.out.println(e);
}
/*manual prepared by www.gr-solution.blogspot.com*/
}
voidgenerateSymmetricKey() {
try {
Random r = new Random();
intnum = r.nextInt(10000);
String knum = String.valueOf(num);
byte[] knumb = knum.getBytes();
skey=getRawKey(knumb);
skeyString = new String(skey);
System.out.println("DES Symmetric key = "+skeyString);
}
catch(Exception e) {
System.out.println(e);
}
}
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGeneratorkgen = KeyGenerator.getInstance("DES");
SecureRandomsr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(56, sr);

25
SecretKeyskey = kgen.generateKey();
raw = skey.getEncoded();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpecskeySpec = new SecretKeySpec(raw, "DES");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
/*manual prepared by www.gr-solution.blogspot.com*/
private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
SecretKeySpecskeySpec = new SecretKeySpec(raw, "DES");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
public static void main(String args[]) {
DES des = new DES();
}
}

26
OUTPUT:

27
RESULT:
Thus the program to implement the DES in java has been executed and the output was verified
successfully.

28
EX NO:2(b) RSA ALGORITHM

AIM:

To implement the RSA Algorithm in java

ALGORITHM:

Start the program.


Declare the class and required variables.
Declare the constructor and destructor of the class.
Implement the RSA Algorithm
Access the member functions using the objects.
Stop the program.

29
PROGRAM:

importjava.io.DataInputStream;
importjava.io.IOException;
importjava.math.BigInteger;
importjava.util.Random;
/*manual prepared by www.gr-solution.blogspot.com*/
public class RSA
{
privateBigInteger p;
privateBigInteger q;
privateBigInteger N;
privateBigInteger phi;
privateBigInteger e;
privateBigInteger d;
privateintbitlength = 1024;
private Random r;

public RSA()
{
r = new Random();
p = BigInteger.probablePrime(bitlength, r);
q = BigInteger.probablePrime(bitlength, r);
N = p.multiply(q);
phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
e = BigInteger.probablePrime(bitlength / 2, r);
while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 &&e.compareTo(phi) < 0)
{
e.add(BigInteger.ONE);
}
d = e.modInverse(phi);
}

public RSA(BigInteger e, BigInteger d, BigInteger N)


{
this.e = e;
this.d = d;
this.N = N;
}

@SuppressWarnings("deprecation")
public static void main(String[] args) throws IOException
{
RSA rsa = new RSA();
DataInputStream in = new DataInputStream(System.in);
String teststring;
System.out.println("Enter the plain text:");
teststring = in.readLine();
System.out.println("Encrypting String: " + teststring);
System.out.println("String in Bytes: "
+ bytesToString(teststring.getBytes()));
// encrypt
byte[] encrypted = rsa.encrypt(teststring.getBytes());
// decrypt
byte[] decrypted = rsa.decrypt(encrypted);

30
System.out.println("Decrypting Bytes: " + bytesToString(decrypted));
System.out.println("Decrypted String: " + new String(decrypted));
}

private static String bytesToString(byte[] encrypted)


{
String test = "";
for (byte b : encrypted)
{
test += Byte.toString(b);
}
return test;
}
/*manual prepared by www.gr-solution.blogspot.com*/
// Encrypt message
public byte[] encrypt(byte[] message)
{
return (new BigInteger(message)).modPow(e, N).toByteArray();
}

// Decrypt message
public byte[] decrypt(byte[] message)
{
return (new BigInteger(message)).modPow(d, N).toByteArray();
}
}

31
OUTPUT:

RESULT:
Thus the program to implement the RSA algorithm in java has been executed and the output was
verified successfully.

32
EX NO:2(c) DIFFIEE-HELLMAN

AIM:

To implement the Diffiee-Hellman in java

ALGORITHM:

Start the program.


Declare the class and required variables.
Declare the constructor and destructor of the class.
Implement the Diffiee-Hellman
Access the member functions using the objects.
Stop the program.

33
PROGRAM :
import java.io.*;
importjava.math.BigInteger;
classDeffie
{
public static void main(String[]args)throws IOException
{
BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter prime number:");
BigInteger p=new BigInteger(br.readLine());
System.out.print("Enter primitive root of "+p+":");
BigInteger g=new BigInteger(br.readLine());
System.out.println("Enter value for x less than "+p+":");
BigInteger x=new BigInteger(br.readLine());
/*manual prepared by www.gr-solution.blogspot.com*/
BigInteger R1=g.modPow(x,p);
System.out.println("R1="+R1);
System.out.print("Enter value for y less than "+p+":");
BigInteger y=new BigInteger(br.readLine());
BigInteger R2=g.modPow(y,p);
System.out.println("R2="+R2);
/*manual prepared by www.gr-solution.blogspot.com*/
BigInteger k1=R2.modPow(x,p);
System.out.println("Key calculated at Alice's side:"+k1);
BigInteger k2=R1.modPow(y,p);
System.out.println("Key calculated at Bob's side:"+k2);
System.out.println("deffiehellman secret key Encryption has Taken");
}
}

34
OUTPUT:

Enter prime number:


11
Enter primitive root of 11:7
Enter value for x less than 11:
3
R1=2
Enter value for y less than 11:6
R2=4
Key calculated at Alice's side:9
Key calculated at Bob's side:9
deffiehellman secret key Encryption has Taken

RESULT:
Thus the program to implement the Diffiee-Hellman in java has been executed and the output was
verified successfully.

35
EX NO:2(d) MD5

AIM:

To implement MD5 algorithm in java

ALGORITHM:

Start the program.


Declare the class and required variables.
Declare the constructor and destructor of the class.
Implement MD5 ALGORITHM IN JAVA
Access the member functions using the objects.
Stop the program.

36
PROGRAM :

public class MD5


{
private static final int INIT_A = 0x67452301;
private static final int INIT_B = (int) 0xEFCDAB89L;
private static final int INIT_C = (int) 0x98BADCFEL;
private static final int INIT_D = 0x10325476;
private static final int[] SHIFT_AMTS = { 7, 12, 17, 22, 5, 9, 14, 20, 4,
11, 16, 23, 6, 10, 15, 21 };
private static final int[] TABLE_T = new int[64];
static
{
for (int i = 0; i < 64; i++)
TABLE_T[i] = (int) (long) ((1L << 32) * Math.abs(Math.sin(i + 1)));
}

public static byte[] computeMD5(byte[] message)


{
int messageLenBytes = message.length;
int numBlocks = ((messageLenBytes + 8) >>> 6) + 1;
int totalLen = numBlocks << 6;
byte[] paddingBytes = new byte[totalLen - messageLenBytes];
paddingBytes[0] = (byte) 0x80;
long messageLenBits = (long) messageLenBytes << 3;
for (int i = 0; i < 8; i++)
{
paddingBytes[paddingBytes.length - 8 + i] = (byte) messageLenBits;
messageLenBits >>>= 8;
}
int a = INIT_A;
int b = INIT_B;
int c = INIT_C;
int d = INIT_D;
int[] buffer = new int[16];
/*manual prepared by www.gr-solution.blogspot.com*/
for (int i = 0; i < numBlocks; i++)
{
int index = i << 6;
for (int j = 0; j < 64; j++, index++)
buffer[j >>> 2] = ((int) ((index < messageLenBytes) ? message[index]
: paddingBytes[index - messageLenBytes]) << 24)
| (buffer[j >>> 2] >>> 8);
int originalA = a;
int originalB = b;
int originalC = c;
int originalD = d;
/*manual prepared by www.gr-solution.blogspot.com*/
for (int j = 0; j < 64; j++)
{
int div16 = j >>> 4;
int f = 0;
int bufferIndex = j;
switch (div16)

37
{
case 0:
f = (b & c) | (~b & d);
break;
case 1:
f = (b & d) | (c & ~d);
bufferIndex = (bufferIndex * 5 + 1) & 0x0F;
break;
case 2:
f = b ^ c ^ d;
bufferIndex = (bufferIndex * 3 + 5) & 0x0F;
break;
case 3:
f = c ^ (b | ~d);
bufferIndex = (bufferIndex * 7) & 0x0F;
break;
}
int temp = b
+ Integer.rotateLeft(a + f + buffer[bufferIndex]
+ TABLE_T[j],
SHIFT_AMTS[(div16 << 2) | (j & 3)]);
a = d;
d = c;
c = b;
b = temp;
}
a += originalA;
b += originalB;
c += originalC;
d += originalD;
}
byte[] md5 = new byte[16];
int count = 0;
for (int i = 0; i < 4; i++)
{
int n = (i == 0) ? a : ((i == 1) ? b : ((i == 2) ? c : d));
for (int j = 0; j < 4; j++)
{
md5[count++] = (byte) n;
n >>>= 8;
}
}
return md5;
/*manual prepared by www.gr-solution.blogspot.com*/
}

public static String toHexString(byte[] b)


{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < b.length; i++)
{
sb.append(String.format("%02X", b[i] & 0xFF));
}
return sb.toString();
}

38
public static void main(String[] args)
{
String[] testStrings = { "", "Sanfoundry", "Message Digest",
"abcdefghijklmnopqrstuvwxyz" };
for (String s : testStrings)
System.out.println("0x" + toHexString(computeMD5(s.getBytes()))
+ " <== \"" + s + "\"");
return;
}
}

39
OUTPUT:

RESULT:
Thus the program to implement the MD5 Algorithm in java has been executed and the output was
verified successfully.

40
EX NO: 2(E) SHA-1

AIM:

To implement the SHA-1 algorithm in java

ALGORITHM:

Start the program.


Declare the class and required variables.
Implement the SHA-1 algorithm
Create the object for the class in the main program.
Access the member functions using the objects.
Stop the program.

41
PROGRAM:

importjava.security.MessageDigest;
importjava.security.NoSuchAlgorithmException;
/*manual prepared by www.gr-solution.blogspot.com*/
public class HashTextTest {

/**
* @paramargs
* @throws NoSuchAlgorithmException
*/
public static void main(String[] args) throws NoSuchAlgorithmException {
System.out.println("Encryption text is=");
System.out.println(sha1("test string to sha1"));
}
/*manual prepared by www.gr-solution.blogspot.com*/
static String sha1(String input) throws NoSuchAlgorithmException {
MessageDigestmDigest = MessageDigest.getInstance("SHA1");
byte[] result = mDigest.digest(input.getBytes());
StringBuffersb = new StringBuffer();
for (inti = 0; i<result.length; i++) {
sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
}

returnsb.toString();
}
}

42
OUTPUT:

RESULT:
Thus the program to implement the SHA-1 algorithm in java has been executed and the output
was verified successfully.

43
EX NO:3 Implement the SIGNATURE SCHEME - Digital Signature Standard

AIM:

To Implement a SIGNATURE SCHEME - Digital Signature Standard in java

ALGORITHM:

Start the program.


Declare the class and required variables.
Implement the SIGNATURE SCHEME - Digital Signature Standard
Create the object for the class in the main program.
Access the member functions using the objects.
Stop the program.

44
PROGRAM:

PublicKeyUtil.java

importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.security.Key;
importjava.security.KeyFactory;
importjava.security.KeyPair;
importjava.security.KeyPairGenerator;
importjava.security.NoSuchAlgorithmException;
importjava.security.PrivateKey;
importjava.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
/*manual prepared by www.gr-solution.blogspot.com*/
public class PublicKeyUtil {

/**
* Generates KeyPair specific to given algorithm
*
* @param algorithm
* @return
* @throws NoSuchAlgorithmException
*/
public static KeyPairgetKeyPair(String algorithm)
throwsNoSuchAlgorithmException {
KeyPairGeneratorkeyPairGenerator = KeyPairGenerator
.getInstance(algorithm);
returnkeyPairGenerator.generateKeyPair();
}

/**
* Return PublicKey from given KeyPair
*
* @paramkeyPair
* @return
*/
public static PublicKeygetPublicKey(KeyPairkeyPair) {
returnkeyPair.getPublic();
}

/**
* Return PrivateKey from given KeyPair
*
* @paramkeyPair
* @return
*/

45
public static PrivateKeygetPrivateKey(KeyPairkeyPair) {
returnkeyPair.getPrivate();
}
/*manual prepared by www.gr-solution.blogspot.com*/
/**
* Convert key to string.
*
* @param key
*
* @return String representation of key
*/
public static String keyToString(Key key) {
/* Get key in encoding format */
byte encoded[] = key.getEncoded();

/*
* Encodes the specified byte array into a String using Base64 encoding
* scheme
*/
String encodedKey = Base64.getEncoder().encodeToString(encoded);

returnencodedKey;
}

/**
* Save key to a file
*
* @param key
* : key to save into file
* @paramfileName
* : File name to store
*/
public static void saveKey(Key key, String fileName) {
byte[] keyBytes = key.getEncoded();
File keyFile = new File(fileName);
FileOutputStreamfOutStream = null;
try {
fOutStream = new FileOutputStream(keyFile);
fOutStream.write(keyBytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fOutStream != null) {
try {
fOutStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

46
/**
* Returns the key stored in a file.
*
* @paramfileName
* @return
* @throws Exception
*/
public static byte[] readKeyFromFile(String fileName) throws Exception {
FileInputStreamkeyfis = new FileInputStream(fileName);
byte[] key = new byte[keyfis.available()];
keyfis.read(key);
keyfis.close();
return key;
}

/**
* Generates public key from encoded byte array.
*
* @param encoded
* @param algorithm
* @return
* @throws Exception
*/
public static PublicKeyconvertArrayToPubKey(byte encoded[],
String algorithm) throws Exception {
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encoded);
KeyFactorykeyFactory = KeyFactory.getInstance(algorithm);
PublicKeypubKey = keyFactory.generatePublic(pubKeySpec);

returnpubKey;
}

/**
* Generates private key from encoded byte array.
*
* @param encoded
* @param algorithm
* @return
* @throws Exception
*/
public static PrivateKeyconvertArrayToPriKey(byte encoded[],
String algorithm) throws Exception {
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
KeyFactorykeyFactory = KeyFactory.getInstance(algorithm);
PrivateKeypriKey = keyFactory.generatePrivate(keySpec);
returnpriKey;
}

47
SignatureUtil.java

importjava.io.BufferedInputStream;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.security.PrivateKey;
importjava.security.Signature;

public class SignatureUtil {

/**
* Generates signature by taking file, PrivateKey and algorithm as input.
*
* @paramfileName
* : Generate signature for this file.
* @paramprivateKey
* @param algorithm
* @return
* @throws Exception
*/
public static byte[] getSignature(String fileName, PrivateKeyprivateKey,
String algorithm) throws Exception {

/* Get instance of Signature object */


Signature signature = Signature.getInstance(algorithm);

/* Initialize Signature object */


signature.initSign(privateKey);

/* Feed data */
feedData(signature, fileName);

/* Generate signature */
byte[] finalSig = signature.sign();

returnfinalSig;
}

/**
* Save signature to a file
*
* @paramfileName
* : Signature saved here
* @param signature
* @throws Exception
*/
public static void saveSignature(String fileName, byte[] signature)
throws Exception {
FileOutputStreamsigfos = new FileOutputStream(fileName);
sigfos.write(signature);

48
sigfos.close();
}

/**
* Read signature from a file and convert it into byte array.
*
* @paramfileName
* : contains signature information
* @return signature as byte array
* @throws Exception
*/
public static byte[] readSignatureFromFile(String fileName)
throws Exception {
returnPublicKeyUtil.readKeyFromFile(fileName);
}

/**
* Feed data to Signature instance
*
* @param signature
* @paramfileName
* @throws Exception
*/
public static void feedData(Signature signature, String fileName)
throws Exception {
/* Supply the Signature Object the Data to Be Signed */
FileInputStreamfis = new FileInputStream(fileName);
BufferedInputStreambufin = new BufferedInputStream(fis);
byte[] buffer = new byte[1024];
intlen;
while ((len = bufin.read(buffer)) >= 0) {
signature.update(buffer, 0, len);
}
bufin.close();
}

TestDigitalSignature.java

importjava.security.KeyPair;
importjava.security.PrivateKey;
importjava.security.PublicKey;
importjava.security.Signature;

//import PublicKeyUtil.*;
//import SignatureUtil.*;

public class TestDigitalSignature {


public static void main(String args[]) throws Exception {

49
String file = "emp.txt";

/* Public key stored in this file */


String publicKeyFile = "publicKey.txt";

/* Signature of given file stored here */


String signatureFile = "siganture.txt";

/* Signature algorithm to get Signature instance */


String sigAlgorithm = "SHA1withDSA";

/* generate public and private keys */


KeyPairkeyPair = PublicKeyUtil.getKeyPair("DSA");
PublicKeypublicKey = keyPair.getPublic();
PrivateKeyprivateKey = keyPair.getPrivate();

/* Generate signature for given file */


byte signature[] = SignatureUtil.getSignature(file, privateKey,
sigAlgorithm);

/* Save public key */


PublicKeyUtil.saveKey(publicKey, publicKeyFile);

/* Save signature */
SignatureUtil.saveSignature(signatureFile, signature);

// Verify Signature

/* Read public key from file */


byte[] pubKeyBytes = PublicKeyUtil.readKeyFromFile(publicKeyFile);

/* Convert publick key bytes into PublicKey object */


PublicKeypubKey = PublicKeyUtil.convertArrayToPubKey(pubKeyBytes,
"DSA");

/* Read signature from file */


byte[] receivedSignature = SignatureUtil
.readSignatureFromFile(signatureFile);

/* Verify signature */
Signature verifySignature = Signature.getInstance(sigAlgorithm);

/* initialize signature object */


verifySignature.initVerify(pubKey);

/* Feed data */
SignatureUtil.feedData(verifySignature, file);

/* Verify signature */
booleanisAuthenticated = verifySignature.verify(receivedSignature);

50
if (isAuthenticated) {
System.out.println("Data is authenticated");
} else {
System.out.println("Data is not from expected sender");
}

}
}

51
OUTPUT:

52
RESULT:
Thus the program to implement the SIGNATURE SCHEME - Digital Signature Standard in java
has been executed and the output was verified successfully.

53
EX NO:4 Demonstrate how to provide secure data storage, secure data transmission and for
creating digital signatures (GnuPG).
AIM:
To Demonstrate how to provide secure data storage, secure data transmission and for creating
digital signatures (GnuPG).

PROCEDURE:
Generating key:
Step 1: Generate Key by click on menu keys->new keys->following dialog box will open
User: Giant Leap Lab
Email: hello@giantleaplab.com
Passphrase: My top secret phrase for decryption

Storing the key in your system.

54
Enter your secrete Passphrase. it consist of at least one number and special character with
length of more than 6

Now your key is generated

Step 2:Encrypting the file:

Go to Files->open(Choose Which file you going to encrypt)-> select the file and click
encrypt->it shows the private keys that you generated before(eg: Giant Leap Lab) select one
of the key now your file will be encrypted.

Choose the key to encrypt the file

55
Your file will encrypted with extension .gpg.

Step 3:Decrypting the file:

Go to Files->open(Choose Which file you going to decrypt)->Now it ask Passphrase that you
have enter while generating the key(passphrase is correct)->your file will be decrypted.

56
Your original file will be displayed with its extension

Note that in commands below where you have to refer to the keys you can either use the username
Giant Leap Lab or the email hello@giantleaplab.com. Store your key in folder

RESULT:
Thus the program to demonstrate how to provide secure data storage, secure data transmission
and for creating digital signatures (GnuPG) has been executed and the output was verified
successfully.

57
EX NO:5 Setup a honey pot and monitor the honeypot on network (KF Sensor)

AIM:
To Setup a honey pot and monitor the honeypot on network (KF Sensor).
PROCEDURE:
HONEYPOTS

When it comes to computer security, honeypots are all the rage. Honeypots can detect
unauthorized activities that might never be picked up by a traditional intrusion detection system.
Furthermore, since almost all access to a honeypot is unauthorized, nearly everything in a honeypot's
logs is worth paying attention to. Honeypots can act as a decoy to keep hackers away from your
production servers. At the same time though, a honeypot can be a little tricky to deploy. In this article,
I will walk you through the process of deploying a honeypot.

INTRODUCTION

There are many different types of honeypot systems. Honeypots can be hardware appliances
or they can be software based. Software based firewalls can reside on top of a variety of operating
systems. For the most part though, honeypots fall into two basic categories; real and virtual.

A virtual honeypot is essentially an emulated server. There are both hardware and software
implementations of virtual honeypots. For example, if a network administrator was concerned that
someone might try to exploit an FTP server, the administrator might deploy a honeypot appliance that
emulates an FTP server.

Downloading and installing KF Sensor

The KF Sensor download consists of a 1.7 MB self-extracting executable file.


Download the file and copy it into an empty folder on your computer.
When you double click on the file, it will launch a very basic Setup program.
The only thing special that you need to know about the Setup process is that it will
require a reboot.

58
Using KFSensor

Step1: you will see the main KFSensor screen shown

As you can see, the column on the left contains a list of port numbers and what the port is
typically used for.

If the icon to the left of a port listing is green, it means that KFSensor is actively monitoring that
port for attacks.

If the icon is blue, it means that there has been an error and KFSensor is not watching for
exploits aimed at that particular port.

Testing the software

Once you've got the software up and running, one of the best things that you can do is to test
the software by launching a port scan against the machine that's running KFSensor.

For the port scan, we using the HostScan.

It simply scans a block of IP addresses, looking for open ports. Figure B shows how the KFSensor
reacts to a partial port scan.

59
If you look at Figure B, you will notice that the icons next to ports that were scanned
turn red to indicate recent activity.

Modifying the Honeypot's behavior

To create or modify rules, select the Edit Active Scenario command from the
Scenario menu.

When you do, you will see a dialog box which contains a summary of all of the
existing rules.

You can either select a rule and click the Edit button to edit a rule, or you can click
the Add button to create a new rule.

Both procedures work similarly.

60
Click the Add button and you will see the Add Listen dialog box, shown in Figure D.
The first thing that this dialog box asks for is a name. This is just a name for the rule.
Pick something descriptive though, because the name that you enter is what will show up in
the logs whenever the rule is triggered.

Click on Add Button

61
Click on Edit Button

The next few fields are protocol, port, and Bind Address. These fields allow you to choose
what the rule is listening for. For example, you could configure the rule to listen to TCP port
1023 on IP address 192.168.1.100. The bind address portion of the rule is optional though. If
you leave the bind address blank, the rule will listen across all of the machine's NICs.

Now that you have defined the listener, it's time to configure the action that the rule takes
when traffic is detected on the specified port. Your options are close, read and close, Sim
Banner, and SimStd Server.

The close option tells the rule to just terminate the connection. Read and close logs the
information and then terminates the connection. The SimStd Server and Sim Banner options
pertain to server emulation. The Sim Banner option allows you to perform a very simple
server emulation, such as what you might use to emulate an FTP server.

The Sim STD Server option allows you to emulate a more complex server, such as an IIS
server.

If you choose to use one of the sim options, you will have to fill in the simulator's name just
below the Time Out field.

The other part of the Action section that's worth mentioning is the severity section. KFSensor
treated some events as severe and other events as a more moderate threat. The dialog box's
Severity drop down list allows you to determine what level of severity should be associated
with the event that you are logging.

62
The final portion of the Add Listen dialog box is the Visitor DOS Attack Limits section. This
section allows you to prevent denial of service attacks against KFSensor. You can determine
the maximum number of connections to the machine per IP address (remember that this
applies on a per rule basis).

If your threshold is exceeded, you can choose to either ignore the excessive connections or
you can lock out the offending IP address.

Now that you have configured the new rule, select the Active Button to Enable/Disable. The
new rule should now be in effect.

RESULT:
Thus the program to setup a honey pot and monitor the honeypot on network (KF Sensor) has
been executed and the output was verified successfully.

63
EX NO:6 Installation of rootkits and study about the variety of options

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

PROCEDURE:

A rootkit is a stealthy type of malicious software (malware) designed to hide the existence of certain
processes or programs from normal methods of detection and enables continued privileged access to a
computer.[1] The term rootkit is a concatenation of "root" (the traditional name of the privileged
account on Unix operating systems) and the word "kit" (which refers to the software components that
implement the tool). The term "rootkit" has negative connotations through its association with
malware.[1]

A rootkit is a collection of tools (programs) that enable administrator-level access to a computer or


computer network. Typically, a cracker installs a rootkit on a computer after first obtaining user-level
access, either by exploiting a known vulnerability or cracking a password. Once the rootkit is
installed, it allows the attacker to mask intrusion and gain root or privileged access to the computer
and, possibly, other machines on the network.

A rootkit may consist of spyware and other programs that: monitor traffic and keystrokes; create a
"backdoor" into the system for the hacker's use; alter log files; attack other machines on the network;
and alter existing system tools to escape detection.

Steps :
1. Double click on rootkit folder.
2. Double click on the GMER rootkit application.
3. Now the rootkit screen will be displayed.

64
4. Select anyone of the drive which is shown at right side of the screen.
5. After selecting the drive click on scan button.

6. Click on the option processes the screen will be displayed

7. Click on the option services.

65
8. Now click on different options to perform different actions.

RESULT:
Thus the program to installation of rootkits and study about the variety of options has been
executed and the output was verified successfully.

66
EX NO 7 PERFORM WIRELESS AUDIT ON AN ACCESS POINT OR A
ROUTER AND DECRYPT WEP AND WPA

AIM:

To develop a workspace using Net Stumbler to perform wireless audit on an access


point or a router and decrypt WEP and WAP

PROCEDURE:

Step 1: Download and install Netstumbler


Step 2: It is highly recommended that your PC should have wireless network card in
order to access wireless router.
Step 3: Now Run Netstumbler in record mode and configure wireless card.
Step 4: There are several indicators regarding the strength of the signal, such as
GREEN
Indicates Strong, YELLOW and other color indicates a weaker signal, RED indicates
a
Very weak and GREY indicates a signal loss.
Step 5: Lock symbol with GREEN bubble indicates the Access point has encryption
enabled.
Step 6: MAC assigned to Wireless Access Point is displayed on right hand pane.
Step 7: The next column displays the Access points Service Set Identifier [SSID]
which is useful to crack the password.
Step 8: To decrypt use Wire Shark tool by selecting Edit preferences IEEE 802.11
Step 9: Enter the WEP keys as a string of hexadecimal numbers as A1B2C3D4E5

NetStumbler (Network Stumbler) is one of the Wi-Fi hacking tool which only
compatible with windows, this tool also a freeware. With this program, we can search for
wireless network which open and infiltrate the network. Its having some compatibility and
network adapter issues.

67
Download and install Netstumbler
It is highly recommended that your PC should have wireless network card in order to
access wireless router.
Now Run Netstumbler in record mode and configure wireless card.
There are several indicators regarding the strength of the signal, such as GREEN
indicates
Strong, YELLOW and other color indicates a weaker signal, RED indicates a very
weak and GREY indicates a signal loss.
Lock symbol with GREEN bubble indicates the Access point has encryption enabled.
MAC assigned to Wireless Access Point is displayed on right hand pane.
The next coloumn displays the Access points Service Set Identifier[SSID] which is
useful to crack the password.
To decrypt use WireShark tool by selecting EditpreferencesIEEE 802.11
Enter the WEP keys as a string of hexadecimal numbers as A1B2C3D4E5

Adding Keys: Wireless Toolbar

If you are using the Windows version of Wireshark and you have an AirPcap adapter you can
add decryption keys using the wireless toolbar. If the toolbar isn't visible, you can show it by
selecting View->Wireless Toolbar. Click on the Decryption Keys... button on the toolbar:

68
RESULT:
Thus the procedure for wireless audit on an access point or a router and
decrypt wep and wpa is done and verified successfully.

69
EX NO:8 Demonstrate intrusion detection system (ids) using any tool (snort or any other sw)

AIM:
To Demonstrate intrusion detection system (ids) using any tool snort.

Introduction

Snort is an open source intrusion detection/prevention system created by Martin "Marty"


Roesch, founder of Sourcefire. It is capable of performing real-time traffic analysis and logging. It is
the most widely used IDS/IPS system. It can monitor for, detect and respond to various attack
strategies by using signature, protocol and anomaly-based inspection techniques.

Installation

The computer we are using for this install has a Dual Core 3GHz processor and 4GB of RAM running
Windows 7 Ultimate (32bit).

First we will start by installing the WinPCap libraries so we can sniff all the packets from our
NIC. Installation of WinPCap is pretty easy. For our installation we will be accepting all of the default
settings. To start the installation, navigate to the location of the WinPCap file we have downloaded.
Right click the file and select "Run as Administrator". You will be presented a title screen.

Just click "Next" to continue to the Welcome screen.


Click "Next" again to continue to the License Agreement screen.
To continue installation of WinPCap, you must agree to the license terms by clicking "I
Agree". If you do not agree to the terms of the license agreement, you will not be able to

70
install WinPCap. Once you click "I Agree", you can continue the installation with Installation
Options.

We will leave these settings as they are and click "Install". This will start the installation process. This
process will not take very long and you will see the Completion screen next.

Click "Finish" to exit the WinPCap setup application.

Now we are ready to move on and install Snort.

To install Snort, navigate to the location of the Snort Installer file. Right click the file and select "Run
as Administrator". As we did with WinPCap, we will also be installing Snort with all the default
settings. The setup application will launch and prompt you to read and agree to the License
Agreement.

Once the files are extracted, we will need to click "Close" to exit the setup application. The setup
application will alert you to make sure a minimum version of WinPCap is installed (which we have
completed) and that

We need to edit the Snort configuration file.

As we were told by the Snort setup application, we will need to change a couple of parameters in the
c:\snort\etc\snort.conf file. To do so, let's use Microsoft's Wordpad application. Open the snort.conf
file and find the lines highlighted below:

71
Once you find these lines, modify them to reflect our default install path (c:\snort) as seen below:

72
Save this file and close Wordpad. We are now ready to use our installation of Snort!

To verify that Snort is installed and running correctly you can run a couple of commands
from the Command Prompt. Open a command prompt as Administrator, switch to the "C:\Snort\Bin"
directory and run "snort.exe -W" to see a list of interfaces available to Snort. The following is output
from the command on Windows :

As you can see, the computer in the example has only one interface with an "Interface" number of "1".

If we wanted to use Snort as a sniffer and watch all traffic on this interface, we could issue the
command "snort.exe -i 1 -v".

This command would run Snort in verbose mode (-v) and have it listen on interface 1 (-i 1). It would
also dump the header of each packet to the screen.

To collect further information, we could use the -d option to capture and display packet payload.
Note: You can use CTRL-C to interrupt the running program.

Let's start Snort as a sniffer to display packet headers and contents. The command we want to enter at
our command prompt is "snort.exe -i 1 -vd".

You can always run Snort with the "-?" option to get a full list of options available. To stop sniffing
packets, break out of the program by pressing Ctrl-C.

You now have Snort running under Windows.

73
Running Snort in Intrusion Detection mode

The problem with running Snort in packet sniffing mode or packet logging mode is that all
packets are logged. This will create a huge amount of information to sort through.

When run in Network Intrusion Detection mode, Snort will not record all packets. The only
packets logged are the ones that match a specific rule. The simplest way to run Snort for intrusion
detection is to log packets in ASCII text to a hierarchical directory structure. If no log file is specified,
packets are logged to /var/snort /log.

To run Snort for intrusion detection and log all packets relative to the 192.168.10.0 network,
use the command:

snort -d -h 192.168.10.0 -l -c snort.conf

The option -c snort.conf tells Snort to use the default /etc/snort.conf file created when Snort was
installed. This file instructs Snort to use all of the rule sets contained in the lib files created
in /etc/snort when Snort was installed.

RESULT:
Thus the program to demonstrate intrusion detection system (ids) using any tool snort has been
executed and the output was verified successfully.

74
EX NO: 9 MONOALPHABETIC CIPHER

AIM:

To implement the MONO CIPHER in java.

ALGORITHM

Start the program.


Declare the class and required variables.
Implement the Monoalphabetic cipher in java
Create the object for the class in the main program.
Access the member functions using the objects.
Stop the program.

75
PROGRAM

package com.sanfoundry.setandstring;
import java.util.Scanner;
public class MonoalphabeticCipher
{
public static char p[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z' };
public static char ch[] = { 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O',
'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C',
'V', 'B', 'N', 'M' };
public static String doEncryption(String s)
{
char c[] = new char[(s.length())];
for (int i = 0; i < s.length(); i++)
{
for (int j = 0; j < 26; j++)
{
if (p[j] == s.charAt(i))
{
c[i] = ch[j];
break;
}
}
}
return (new String(c));
}

public static String doDecryption(String s)


{
char p1[] = new char[(s.length())];
for (int i = 0; i < s.length(); i++)
{
for (int j = 0; j < 26; j++)
{
if (ch[j] == s.charAt(i))
{
p1[i] = p[j];
break;
}
}
}
return (new String(p1));
}

public static void main(String args[])


{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the message: ");
String en = doEncryption(sc.next().toLowerCase());
System.out.println("Encrypted message: " + en);
System.out.println("Decrypted message: " + doDecryption(en));
sc.close();
}

76
OUTPUT
$ javac MonoalphabeticCipher.java
$ java MonoalphabeticCipher

Enter the message:


Sanfoundry
Encrypted message: LQFYGXFRKN
Decrypted message: sanfoundry

RESULT:
Thus the program to implement the MONO CIPHER in java has been executed and the output
was verified successfully.

77
EX NO:10 TRIPLE DES

AIM:

To implement the TRIPLE DES in java.

ALGORITHM

Start the program.


Declare the class and required variables.
Declare the constructor and destructor of the class.
Implement the TRIPLE DES in java
Access the member functions using the objects.
Stop the program.

78
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");


}
}

79
OUTPUT

RESULT:
Thus the program to implement the TRIPLE DES in java has been executed and the output was
verified successfully.

80

You might also like