Security Lab Manual1
Security Lab Manual1
Security Lab Manual1
Aim
To implement the Caesar cipher in java.
Algorithm
Step 1: Start the Program
Step 2: Initialize the Variable
Step 3: Caesar cipher (shift cipher) is a simple substitution cipher based on a replacement of
Every single character.
Step 4: The alphabet is shifted by an arbitrary number of positions. The number of positions
is the key-value. shifting the bottom alphabet 3 positions to the right yields the following
result:
abcdefghijklmnopqrstuvwxyz
defghijklmnopqrstuvwxyzabc
Step 5: The encryption can be described with the following formula:
c =e(p) = (p+3) mod 26
a shift may be any amount, so that general caesar algorithm is
c = e (p) = (p+k) mod 26
Step 6: The process of decryption uses reverted procedure:
p = d(c) = (c-k) mod 26
Step 7: stop the program.
Program:
import java.util.Scanner;
public class Caesar
{
public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
public static String encrypt(String plainText, int shiftKey)
{
plainText = plainText.toLowerCase();
String cipherText = "";
for (int i = 0; i < plainText.length(); i++)
{
int charPosition = ALPHABET.indexOf(plainText.charAt(i));
int keyVal = (shiftKey + charPosition) % 26;
char replaceVal = ALPHABET.charAt(keyVal);
cipherText += replaceVal;
}
return cipherText;
}
public static String decrypt(String cipherText, int shiftKey)
{
cipherText = cipherText.toLowerCase();
1
String plainText = "";
for (int i = 0; i < cipherText.length(); i++)
{
int charPosition = ALPHABET.indexOf(cipherText.charAt(i));
int keyVal = (charPosition - shiftKey) % 26;
if (keyVal < 0)
{
keyVal = ALPHABET.length() + keyVal;
}
char replaceVal = ALPHABET.charAt(keyVal);
plainText += replaceVal;
}
return plainText;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String for Encryption: ");
String message = new String();
message = sc.next();
System.out.println(encrypt(message, 6));
System.out.println(decrypt(encrypt(message, 3), 3));
sc.close();
}
}
Output :
Enter the String for Encryption:
issac
Encrypted String
lvvdf
Decrypted String
issac
Result:
Thus the Caesar Cipher program has been successfully implemented and the output was
verified.
2
EX NO: 1(B) PLAYFAIR CIPHER
DATE:
Aim:
To implement a playfair cipher in java.
Algorithm:
STEP 1: Start the program
STEP 2: Construct 5X5 matrix of letters based on a keyword
STEP 3: Fill in letters of keyword.
STEP 4:Fill rest of matrix with other letters
eg. Using the keyword MONARCHY
MONAR
CHYBD
E F G I/J K
LPQST
UVWXZ
STEP 5: plaintext is encrypted two letters at a time
If a pair is a repeated letter, insert filler like 'X‟
If both letters fall in the same row, replace each with letter to right.
If both letters fall in the same column, replace each with the letter below.
Otherwise each letter is replaced by the letter in the same row and in the
column of the other letter of the pair
STEP 6: Break the plaintext in a two character diagram:
Plaintext is divided into 2-letter diagram
Use X to separate double letter
Use X to pad the last single letter
STEP 7: Terminate the program.
PROGRAM
import java.util.Scanner;
public class playfaircipherencryption
{
private String KeyWord = new String();
private String Key = new String();
private char matrix_arr[][] = new char[5][5];
3
if (flag == false)
K_adjust = K_adjust + k.charAt(i);
flag = false;
}
KeyWord = K_adjust;
}
public void KeyGen()
{
boolean flag = true;
char current;
Key = KeyWord;
for (int i = 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;
}
System.out.println(Key);
matrix();
}
private void matrix()
{
int counter = 0;
for (int i = 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)
{
int i = 0;
int len = 0;
String text = new String();
len = old_text.length();
for (int tmp = 0; tmp < len; tmp++)
4
{
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];
int counter = 0;
for (int i = 0; i < size / 2; i++)
{
x[i] = Original.substring(counter, counter + 2);
counter = counter + 2;
}
return x;
}
public int[] GetDiminsions(char letter)
{
int[] key = new int[2];
if (letter == 'j')
letter = 'i';
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
if (matrix_arr[i][j] == letter)
{
key[0] = i;
key[1] = j;
break;
5
}
}
}
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 (int i = 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])
{
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]];
}
6
return Code;
}
Output:
Enter a keyword:
hai
haibc
defgk
lmnop
qrs tu
vwxyz
Enter word to encrypt: (Make sure length of message is even)
Newton
mfyrpo
Result:
Thus the Playfair Cipher program has been successfully implemented and the output was
verified.
7
EX. NO: 1C HILL CIPHER
DATE:
Aim:
To Write a JAVA program to generate Hill cipher.
Algorithm:
STEP 1: Start the program
STEP 2: The Hill Cipher uses matrix multiplication to encrypt a message.
STEP 3: convert letters into number-pair:
Use the table and 00 for spaces:
ABCDEFGHIJKLMNOPQRS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
TUVWXYZ
20 21 22 23 24 25 26
STEP 4: Now using the key, Make the first pair a column vector, and multiply that matrix by
the key. Using the formula C=PK mod 26 to get the cipher text.
STEP 5: K-1 is applied to the cipher text, and then the plain text is recovered.
P=C K-1mod26
STEP 6: Terminate the program.
Program:
import javax.swing.JOptionPane;
public class HillCipher {
//the 3x3 key matrix for 3 characters at once
public static int[][] keymat = new int[][]{
{ 1, 2, 1 },
{ 2, 3, 2 },
{ 2, 2, 1 },
};
public static int[][] invkeymat = new int[][]{
{ -1, 0, 1 },
{ 2, -1, 0 },
{ -2, 2, -1},
};
public static String key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static void main(String[] args) {
// TODO code application logic here
String text,outtext ="";
int ch, n;
ch = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter 1 to Encrypt and 2 to
Decrypt!"));
text = JOptionPane.showInputDialog(null, "Enter plain/cipher text to encrypt?");
text = text.toUpperCase();
text = text.replaceAll("\\s",""); //removing spaces
n = text.length() % 3;
if(n!=0){
for(int i = 1; i<= (3-n);i++){
text+= 'X';
8
}}
System.out.println("Padded Text:" + text);
char[] ptextchars = text.toCharArray();
switch(ch){
case 1:
for(int i=0;i< text.length(); i+=3){
outtext += encrypt(ptextchars[i],ptextchars[i+1],ptextchars[i+2]);
}
break;
case 2:
for(int i=0;i< text.length(); i+=3){
outtext += decrypt(ptextchars[i],ptextchars[i+1],ptextchars[i+2]);
}
break;
default: System.out.println("Invalid Choice!");
}
System.out.println("Output: " + outtext);
}
private static String encrypt(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 decrypt(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;
}
}
9
Output:
Encryption process:
Padded Text:THISISHILLCIPHERTECHNIQUEXX
Output: XXPSSATIIFSXLHHLVHQZDCAISTV
Decryption process:
Padded Text:XXPSSATIIFSXLHHLVHQZDCAISTV
Output: THISISHILLCIPHERTECHNIQUEXX
Result:
Thus the Hill Cipher program has been successfully implemented and the output was
verified.
10
EX NO: 1(d) VIGENERE CIPHER
DATE:
Aim:
To implement the vigenere cipher in java.
Algorithm:
STEP 1:Start the program
STEP 2:Declare the class and required variables.
STEP 3:Declare the constructor and destructor of the class.
STEP 4:To encrypt a message, a key is needed that is as long as the message.
Usually, the key is a repeating keyword.
STEP 5:Implement the vigenere cipher Procedure:
Program:
import java.io.*;
public class vignerecipher
{
11
res += (char) ((c - key.charAt(j) + 26) % 26 + 'A');
j = ++j % key.length();
}
return res;
}
public static void main(String[] args) throws IOException
{
BufferedReader vbr=new BufferedReader(new InputStreamReader(System.in));
String key = "VIGENERECIPHER";
System.out.println(" enter the String : " );
String message = vbr.readLine();
String encryptedMsg = encrypt(message, key);
System.out.println("String: " + message);
System.out.println("Encrypted message: " + encryptedMsg);
}
}
Output:
Enter the String :
hai
String: hai
Encrypted message: CIO
Result:
Thus the vigenere cipher program has been successfully implemented and the output was
verified.
12
EX. NO: 1(e) RAILFENCE CIPHER
DATE:
Aim:
To Write a JAVA program to generate Railfence cipher.
Algorithm:
STEP 1: Start the program
STEP 2: The key for the rail fence cipher is just the number of rails. To encrypt a piece of
text,
STEP 3: Write message letters out diagonally over a number of rows then read off cipher
row by row
STEP 4: We write it out in a special way on a number of rails.
STEP 5: The cipher text is read off along the rows.
STEP 6: Stop the program.
Program:
import java.io.*;
public class columnar {
output += input.charAt(i);
}
for(int i=1;i<len;i+=2) {
output += input.charAt(i);
}
Output:
Inputstring:inputstring
Cipher Text:ipttignusrn
Result:
Thus the railfence cipher program has been successfully implemented and the output was
verified.
13
2. IMPLEMENT THE FOLLOWING ALGORITHMS
Aim:
To Write a JAVA program to implement the DES Algorithm.
Algorithm :
STEP 1: Start the program
STEP 2: DES algorithm is designed to encipher and decipher blocks of data consisting of 64
bits under control of a 64-bit key
STEP 3:Permutation is an operation performed by a function, which moves an element at
place to the place k.
STEP 4:The key-dependent computation can be simply defined in terms of a function f,
called the cipher function, and a function KS, called the key schedule.
STEP 5: A definition of the cipher function f that is given in terms of selection function Si
and permutation function P.
STEP 6: LR denotes the block consisting of the bits of L followed by the bits of R.
STEP 7: Stop the program.
Program:
import javax.swing.*;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Random ;
public 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);
14
byte[] dbyte= decrypt(raw,ebyte);
String decryptedMessage = new String(dbyte);
System.out.println("Decrypted message "+decryptedMessage);
}
void generateSymmetricKey() {
try {
Random r = new Random();
int num = 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 {
KeyGenerator kgen = KeyGenerator.getInstance("DES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(56, sr);
SecretKey skey = kgen.generateKey();
raw = skey.getEncoded();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "DES");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
15
public static void main(String args[]) {
DES des = new DES();
}}
OUTPUT:
DES Symmetric key = R�]Q�TC1
Encrypted message �0�=�)������ ��
Decrypted message SECURITYLAB
Result:
Thus the DES Algorithm program has been successfully implemented and the output was
verified.
16
EX.NO:2B RSA ALGORITHM
DATE:
Aim:
To Write a JAVA program to implement the RSA Algorithm.
Algorithm :
STEP 1: Start the program
STEP 2: p and q are two prime numbers.
STEP 3: n = pq
STEP 4: m = (p-1)(q-1)
STEP 5: Message M < n.
STEP 6: Encryption key = (a,n).
STEP 7: Decryption key = (b,n).
STEP 8: Encrypt => E = Ma mod n.
STEP 9: Decrypt => M = Eb mod n.
STEP 10: Stop the program
Program:
import java.io.DataInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Random;
public class rsa
{
private BigInteger p;
private BigInteger q;
private BigInteger N;
private BigInteger phi;
private BigInteger e;
private BigInteger d;
private int bitlength = 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;
17
}
@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);
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;
}
// 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();
}}
Output:
Enter the plain text:
good
Encrypting String: good
String in Bytes: 103111111100
Decrypting Bytes: 103111111100
Decrypted String: good
Result:
Thus the RSA algorithm program has been successfully implemented and the output was
verified.
18
EX.NO:2C DIFFIEE –HELLMAN ALGORITHM
DATE:
Aim:
To Write a JAVA program to implement the Diffiee –Hellman Algorithm.
Algorithm :
STEP 1: Start the program
STEP 2: Alice and Bob exchange their public keys PA and PB.
STEP 3: Alice computes F(SA , PB)
STEP 4: Bob computes F(SB, PA)
STEP 5: Alice and Bob now share a secret.
STEP 6: The system parameters (which are public) are:
a large prime number p – typically 1024 bits in length
a primitive element g.
STEP 7: Calculation of secret key by user A
K = (YB) XA mod q
Calculation of secret key by user A
K= (YA) XB mod q
STEP 8: Stop the program.
Program:
import java.io.*;
import java.math.BigInteger;
class diff
{
public static void main(String[]args)throws IOException
{
BufferedReader br=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());
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);
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("deffie hellman secret key Encryption has Taken"); } }
19
Output:
Enter prime number:
11
Enter primitive root of 11:3
Enter value for x less than 11:
2
R1=9
Enter value for y less than 11:4
R2=4
Key calculated at A side:5
Key calculated at B side:5
Diffie hellman secret key Encryption has Take
Result:
Thus the Diffiee –Hellman Algorithm program has been successfully implemented and the
output was verified
20
EX.NO:2D MD5- ALGORITHM
DATE:
Aim:
To Write a JAVA program to implement the MD5-Alogorithm.
Algorithm:
STEP 1:Start the program.
STEP 2: Suppose a b-bit message as input, and that we need to find its message digest.
STEP 3: MD5 algorithm can be used as a digital signature mechanism.
append padded bits:
The message is padded so that its length is congruent to 448, modulo 512.
STEP 4: append length:
A 64 bit representation of b is appended to the result of the previous step.
STEP 5: Initialize MD Buffer
A four-word buffer (A,B,C,D) is used to compute the message digest.
Here each of A,B,C,D, is a 32 bit register
STEP 6: These registers are initialized to the hexadecimal values.
STEP 7:Terminate the program.
Program:
import java.io.*;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class md1
{
public static String getMD5(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(input.getBytes());
BigInteger number = new BigInteger(1, messageDigest);
String hashtext = number.toString(16);
// Now we need to zero pad it if you actually want the full 32 chars.
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
return hashtext;
}
catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws NoSuchAlgorithmException {
try
{
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
System.out.println(" --------MD5---------");
21
System.out.println("enter the String to Encrypt:");
String inp=br.readLine();
System.out.println("********************* ");
System.out.println("Encrypted String: ");
System.out.println(getMD5(inp));
}
catch(Exception e)
{
System.out.println("error");
}
}
}
Output:
--------MD5---------
enter the String to Encrypt:
message digest
*********************
Encrypted String:
f96b697d7cb7938d525a2f31aaf161d0
Result:
Thus the MD5 Algorithm program has been successfully implemented and the output was
verified
22
EX.NO:2E SHA-1 ALGORITHM
DATE:
Aim:
To Write a JAVA program to implement the SHA-1 Algorithm
Algorithm :
STEP 1: Start the program
STEP 2: Appending Padding Bits. The original message is "padded" (extended) so that its
length is congruent to 448, modulo 512
The original message is always padded with one bit "1" first.
STEP 3: Appending Length. 64 bits are appended to the end of the padded message to
indicate the length of the original message in bytes.
Break the 64-bit length into 2 words .
STEP 4: Preparing Processing Functions. SHA1 requires 80 processing functions.
STEP 5: Preparing Processing Constants. SHA1 requires 80 processing constant words.
STEP 6: Initializing Buffers. SHA1 algorithm requires 5 word buffers with the following
initial
Values.
STEP 7: Processing Message in 512-bit Blocks
STEP 8: Stop the Program.
Program:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class sha11
{
public static void main(String[] args) throws IOException {
BufferedReader userInput = new BufferedReader (new InputStreamReader(System.in));
System.out.println("Enter string:");
String rawString = userInput.readLine();
try {
System.out.println("SHA1 hash of string: " +
AeSimpleSHA1.SHA1(rawString));
} catch ( NoSuchAlgorithmException | UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}}
Output:
Enter string:
encryption algorithm
SHA1 hash of string: 6ea8ecf571036b4c17718dec32a0cb06d951bbca
Result: Thus the SHA-1 Algorithm program has been successfully implemented and the
output was verified
23
EX. NO: 3 Implement the Signature Scheme- Digital Signature Standard
DATE:
Aim:
To Write a JAVA program to implement the SIGNATURE SCHEME- Digital Signature
Standard
Algorithm:
STEP 1: Start the program.
STEP 2: Declare the class and required variables.
STEP 3: Implement the SIGNATURE SCHEME - Digital Signature Standard
Let H be the hashing function and m be the message
STEP 4: Create the object for the class in the main program.
STEP 5: Access the member functions using the objects.
STEP 6: Calculate the signature
S=k-1 (H(m)+xr) mod q
STEP 7: The signature is (r,s)
STEP 8: Compare the values, the signature is invalid unless v==r.
STEP 9: Stop the program.
PublicKeyUtil
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Base64.*;
25
byte[] keyBytes = key.getEncoded();
File keyFile = new File(fileName);
FileOutputStream fOutStream = 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();
} } } }
/**
* Returns the key stored in a file.
*
* @paramfileName
* @return
* @throws Exception
*/
public static byte[] readKeyFromFile(String fileName) throws Exception {
FileInputStream keyfis = 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 PublicKey convertArrayToPubKey(byte encoded[],
String algorithm) throws Exception {
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encoded);
KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
return pubKey;
}
/**
* Generates private key from encoded byte array.
*
* @param encoded
* @param algorithm
* @return
26
* @throws Exception
*/
public static PrivateKey convertArrayToPriKey(byte encoded[],String algorithm) throws
Exception
{
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
PrivateKey priKey = keyFactory.generatePrivate(keySpec);
return priKey;
}
}
SignatureUtil
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.PrivateKey;
import java.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, PrivateKey privateKey,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();
return finalSig;
}
/**
* Save signature to a file
*
* @paramfileName
* : Signature saved here
* @param signature
* @throws Exception
*/
27
public static void saveSignature(String fileName, byte[] signature)
throws Exception {
FileOutputStream sigfos = new FileOutputStream(fileName);
sigfos.write(signature);
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 {
return PublicKeyUtil.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 */
FileInputStream fis = new FileInputStream(fileName);
BufferedInputStream bufin = new BufferedInputStream(fis);
byte[] buffer = new byte[1024];
int len;
while ((len = bufin.read(buffer)) >= 0) {
signature.update(buffer, 0, len);
}
bufin.close();
}
}
TestDigitalSignature
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
//import PublicKeyUtil.*;
//import SignatureUtil.*;
public class TestDigitalSignature {
public static void main(String args[]) throws Exception {
String file = "E:/emp.txt";
28
/* Public key stored in this file */
String publicKeyFile = "E:/publickey.txt";
/* Save signature */
SignatureUtil.saveSignature(signatureFile, signature);
// Verify Signature
/* Verify signature */
Signature verifySignature = Signature.getInstance(sigAlgorithm);
/* Feed data */
SignatureUtil.feedData(verifySignature, file);
/* Verify signature */
boolean isAuthenticated = verifySignature.verify(receivedSignature);
if (isAuthenticated) {
System.out.println("Data is authenticated");
29
}
else
{
System.out.println("Data is not from expected sender");
}
}
}
Output:
30
Result:
Thus the Implementation of the SIGNATURE SCHEME- Digital Signature Standard
program has been successfully implemented and the output was verified
31
EX NO:4 Demonstrate how to provide secure data storage, secure data transmission
and for DATE: creating digital signatures (GnuPG).
Aim:
Demonstrate how to provide secure data storage, secure data transmission and for creating
digital signatures using GnuPG security tool.
PROCEDURE:
Installing Gpg4win
The installation assistant will start and ask you for the language to be used with the
installation process.
Choose all the program that are run on your computer and click on[Next]
The next page displays the licensing agreement – it is only important if you wish to modify or
forward Gpg4win. If you only want to use the software, you can do this right away – without
reading the license.
32
click on[Next]
On the page that contains the selection of components you can decide which programs you
want
to install.
Click on[Next].
33
click on[Next]
Now you can decide which links should be installed – the system will automatically create a
link
with the start menu
click on[Next].
During the installation process that follows, you will see a progress bar and information on
which file is currently being installed.
34
Then click on [ Finish ].
Now open the GPG4Win tool ,to get the following page:
To create a new certificate to click the File menu and new certificate.
35
Click next.
36
To be select the timestamp value. and then click ok
To create a new file .And Write click the file then click Sign and Encrypt option.
38
The following page will be open.Select the option Remove unencrypted original file When
done and then click ok
39
Then click Encrypt option.
40
The file to be encrypted.
41
Then click ok.
Result:
Thus the Demonstration of how to provide secure data storage, secure data transmission and
for creating digital signatures (GnuPG) program has been successfully implemented and the
output was verified
42
EX.NO: 5 SETUP A HONEY POT AND MONITOR THE HONEYPOT ON
NETWORK
DATE:
Aim:
Setup a Honey Pot and monitor the honeypot on Network using KF Sensor Security tool.
PROCEDURE:
INTRODUCTION
Honey Pot is a device placed on Computer Network specifically designed to capture
malicious network traffic.
KF Sensor is the tool to setup as honeypot when KF Sensor is running. Honeypots can
act as a decoy to keep hackers away from your production servers.
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
A virtual honeypot is essentially an emulated server
43
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.
44
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.
If you look at Figure B, you will notice that the icons next to ports that were
scanned turn red to indicate recent activity.
45
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.
46
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.123.9. 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.
The close option tells the rule to just terminate the connection. Read and close logs
the information and then terminates the connection
If your threshold is exceeded, you can choose to either ignore the excessive
connections or you can lock out the offending IP address.
Result:
Thus the setup a honey pot and monitor the honeypot on network has been
successfully implemented and the output was verified
47
EX NO: 6 INSTALLATION OF ROOTKITS AND STUDY ABOUT THE
DATE: VARIETY OF OPTIONS
Aim:
To Installation of rootkits and study about the variety of options.
Procedure:
A rootkit is a collection of tools (programs) that enable administrator-level access to a
computer or computer network
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.
Download Rootkit Tool from GMER website. www.gmer.net
Double click on rootkit folder.
Double click on the GMER rootkit application.
Now the rootkit screen will be displayed.
This displays the Processes, Modules, Services, Files, Registry.
Services menu displays the complete services running with Autostart, Enable,
Disable, System, Boot.
CMD allows the user to interact with command line utilities or Registry.
To be double click the GMER tool ,to get the above page. This displays consists type and
process menu.
48
Registry displays Hkey_Current_user and Hkey_Local_Machine. Rootkits/Malawares scans
the local drives selected
49
Click the process window to get,
50
To select the hard drive and click Scan option.
The rootkit virus to be detected. Write click the file .and then click kill process.
51
The virus to be deleted. again check the process.
Result:
Thus the installation of rootkits and study about the variety of options has been
successfully installed and the output was verified.
EX. NO: 7 PERFORM AN WIRELESS AUDIT OF AN ACCESS POINT /
DATE: ROUTER AND DECRYPT WEP AND WPA
Aim:
To perform an wireless audit of an access point /router and decrypt WEP and WPA using
Net Stumbler
Procedure:
Download and install Vi stumbler
It is highly recommended that your PC should have wireless network card in order
to
access wireless router.Now Run Vi stumbler 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.
52
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 EditàpreferencesàIEEE 802.11
Enter the WEP keys as a string of hexadecimal numbers as A1B2C3D4E5
Click I Agree .
53
After installing the ,it will stored in desktop.
54
The be connect the wifi adaptor ,it will detect the wifi devices.
55
After configuring the devices ,it display the following figures.
Result:
Thus the wireless audit on an access point or a router and decrypt WEP and WPA program
has been successfully executed and the output was verified.
56
EX.NO: 8 DEMONSTRATE INTRUSION DETECTION SYSTEM (IDS)
DATE: USING ANY TOOL
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.
57
Click I Agree.
Click Install.
58
After finishing the installtion, click finish option.
Now we are ready to move on and install Snort.
INSTALL SNORT
Download Snort from "http://www.snort.org/" website.
Also download Rules from the same website. You need to sign up to get rules for
registered users.
Click on the Snort_(version-number)_Installer.exe file to install it. By-default it will
install snort in the "C:\Snort" directory.
Extract downloaded Rules file: snortrules-snapshot-(number).tar.gz
Copy all files from the "rules" directory of the extracted folder and paste them into
"C:\Snort\rules" directory.
Copy "snort.conf" file from the "etc" directory of the extracted folder and paste it into
"C:\Snort\etc" directory. Overwrite existing file if there is any.
59
Click I Agree .
60
Click next.
Tool to be installed.
61
Snort has been successfully installed.
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:
Once you find these lines, modify them to reflect our default install path (c:\snort) as seen
below:
62
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 :
63
Finally run this command
C:\snort\bin>snort -i 1 -l c:\snort\log -c c:\snort\etc\snort.conf -T
-T = Test and report on the current snort configure
You will get the message that
Result:
Thus the Demonstration of intrusion detection system using snort tool has been
successfully executed and the output was verified.
64