0% found this document useful (0 votes)
81 views51 pages

Security Laboratory Record Notebook

The program implements the Playfair cipher encryption algorithm in Java. It takes plaintext as input and encrypts it using a 5x5 key matrix generated from the keyword "MONARCHY". It breaks the plaintext into pairs of letters and applies the Playfair cipher rules to encrypt each pair. The rules involve looking up the letter positions in the matrix and replacing each letter with the letter in the same row/column based on the other letter. The ciphertext output is displayed.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views51 pages

Security Laboratory Record Notebook

The program implements the Playfair cipher encryption algorithm in Java. It takes plaintext as input and encrypts it using a 5x5 key matrix generated from the keyword "MONARCHY". It breaks the plaintext into pairs of letters and applies the Playfair cipher rules to encrypt each pair. The rules involve looking up the letter positions in the matrix and replacing each letter with the letter in the same row/column based on the other letter. The ciphertext output is displayed.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MEENAKSHI SUNDARARAJAN ENGINEERING COLLEGE

Kodambakkam, Chennai 600024

DEPARTMENT OF INFORMATION TECHNOLOGY

IT8761 SECURITY LABORATORY

RECORD NOTE BOOK

Name : SUSEENDRAN K
Register Number :311517205049
Class : IV YEAR IT
Batch :2017-2021
MEENAKSHI SUNDARARAJAN ENGINEERING COLLEGE
Kodambakkam, Chennai-600 024

Certified to be the Bonafide Record of work done by _SUSSENDRAN K Register


No. _311517205049of class IV year ITin IT8761- SECURITY LABORATORY
during the academic Year2020-2021.

Staff-In-Charge HOD

Submitted for the University practical examination held on 17/12/2020at


Meenakshi Sundararajan Engineering College, Kodambakkam, Chennai -
24.

INTERNALEXAMINER EXTERNALEXAMINER
TABLE OF CONTENTS

EX. PAGE
DATE TITLE SIGN
NO. NO.
I SUBSTITUTION & TRANSPOSITION
TECHNIQUES

1 8/7/2020 IMPLEMENTATION OF CAESAR CIPHER 1

IMPLEMENTATION OF PLAYFAIR
2 15/7/2020 4
CIPHER

3 22/7/2020 IMPLEMENTATION OF HILL CIPHER 9

IMPLEMENTATION OF VIGENERE
4 29/7/2020 13
CIPHER
IMPLEMENTATION OF RAIL FENCE
5 8/8/2020 16
CIPHER
IMPLEMENTATION OF ROW AND
6 12/8/2020 COLUMN TRANSFORMATION CIPHER 18

II SYMMETRIC AND PUBLIC KEY


ENCRYPTION ALGORITHMS
IMPLEMENTATION OF DATA
7 26/8/2020 20
ENCRYPTION STANDARD
IMPLEMENTATION OF ADVANCED
8 2/9/2020 22
ENCRYPTION STANDARD
IMPLEMENTATION OF RIVEST SHAMIR
9 9/9/2020 25
ADLEMAN ALGORITHM
IMPLEMENTATION OF DIFFIE-HELLMAN
10 16/9/2020 28
KEY EXCHANGE

III AUTHENTICATION ALGORITHM


IMPLEMENTATION OF SECURE HASH
11 28/10/2020 30
ALGORITHM-1
IV SIGNATURE SCHEME
IMPLEMENTATION OF DIGITAL
12 31/10/2020 32
SIGNATURE STANDARD
V NETWORK SECURITY TOOLS
DEMONSTRATION OF INTRUSION
13
4/11/2020 DETECTION SYSTEM 33
EXPLORATION OF N-STALKER -
14
7/11/2020 VULNERABILITY ASSESSMENT TOOL 37
DEFEATING MALWARE - BUILDING
15
11/11/2020 TROJANS 42
DEFEATING MALWARE - ROOTKIT
16
11/11/2020 HUNTER 44
Ex.No:1 IMPLEMENTATION OF CAESARCIPHER
Date:08/07/2020

AIM:
Write a Java program to perform encryption and decryption using Caesar cipher.
ALGORITHM:
STEP1:Read the plaintext and Replace the letters of plaintext by other letters
STEP 2 :Caesar cipher involves replacing each letter of the alphabet with the letter standing 3
places further down the alphabet.

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
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

STEP3: The formula used for encrypting the message in Caesar cipher such that
C = E(p) = (p+3) mod 26
shift may be any amount, so that general Caesar algorithm is
C = E (p) = (p+k) mod 26 Where k takes on a value in the range 1 to 25.
STEP 4 :The formula used for decrypting the Caesar cipher is P = D(C) = (C-3) mod 26
STEP 5: Display the ciphertext

PROGRAM:
import java.util.Scanner;
public class CaesarCipher
{
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));

1
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();
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, 3));
System.out.println(decrypt(encrypt(message, 3), 3));
sc.close();
}
}

2
OUTPUT:

RESULT:
The Caesar cipher was implemented using Java.

3
Ex.No:2 IMPLEMENTATION OF PLAYFAIRCIPHER
Date:15/07/2020

AIM:
Write a Java program to encrypt the givenplaintextto Playfair ciphertextusingkeyword
“MONARCHY.

ALGORITHM:
STEP 1: Construct a Playfair cipher which is based on 5 X 5 matrix containing a key word or
phrase.
STEP 2: To Generate the key matrix, fill in the spaces in the matrix with the letters of the
keyword (dropping any duplicate letters), then fill the remaining spaces with the rest of the
letters of the alphabet in order (put both "I" and "J" in the same space) to reduce the alphabet to
fit.. The key can be written in the top rows of the table, from left to right.

M O N A R

C H Y B D

E F G I/J K

L P Q S T

U V W X z
STEP 3: To encrypt a message, first break the message
into groups of 2 letters such that, for example, "HelloWorld" becomes "HE LL OW OR LD", and
map them out on the key matrix. If needed, append an uncommon monogram to complete the
finaldiagram.
STEP4:Encrypt two letters of plaintext at a time and Apply the following 4 rules, in order, to
each pair of letters in the plaintext:

STEP 4.1: If both letters are the same ,they are separated by filter letter such as x.Foreg, the
plaintext balloon would be treated as ba lx lo on.

4
STEP4.2:Two plaintext letters that fall in the same row of the matrix are each replaced by the
letter to the right,with the first element of the row circularly following the last.For example, ar is
encryptede as RM.

STEP 4.3:If two plaintext letters that fall in the same column are each replaced by the letter
beneath,with the top element of the column circularly following the last .For example ,mu is
encrypted as CM.

STEP 4.4: If the letters are not on the same row or column, each plaintext letter in a pair is
replaced by the letter that lies in its own row and the column occupied by the other
plaintextletter.Thus ,hs becomes BP and ea becomes IM.
STEP 5: Display the ciphertext produced from the plaintext.

PROGRAM:

import javax.swing.JOptionPane;

public class PlayFair {

public static char[][] keymat = new char[][]{


{ 'M', 'O', 'N', 'A', 'R' },
{ 'C', 'H', 'Y', 'B', 'D' },
{ 'E', 'F', 'G', 'I','K'},
{ 'L', 'P', 'Q', 'S','T'},
{ 'U', 'V', 'W', 'X', 'Z'}
};
public static String trans = "J";
public static char filler = 'X';
public static void main(String args[])

{
String text, outtext="";
int ch;
ch = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter 1 to Encrypt and 2 to
Decrypt!"));
text = JOptionPane.showInputDialog(null, "Enter plain/cipher text to encrypt/decrypt?");
text = text.toUpperCase();
text = text.replaceAll("\\s",""); //removing spaces
text = text.replace(trans, "I"); //changing J with I
text = text.replaceAll("([A-Z])\\1+","$1"+filler+"$1"); //handling repeated letters

5
if(text.length() % 2 !=0)
text+= filler;
char[] ptextchars = text.toCharArray();
System.out.println("Padded Text: "+text);
switch(ch){
case 1:
for(int i=0;i<text.length(); i+=2){
outtext += encrypt(ptextchars[i],ptextchars[i+1]);
}
break;
case 2:
for(int i=0;i<text.length(); i+=2){
outtext += decrypt(ptextchars[i],ptextchars[i+1]);
}
break;
default: System.out.println("Invalid Choice!");
}
System.out.println("Output: "+outtext);
}

private static String encrypt(char c1, char c2) {


int[] posa = new int[2];
int[] posb = new int[2];
String frag = "";
posa = search(c1);
posb = search(c2);
if(posa[0] ==posb[0]){
c1 = keymat[posa[0]][(posa[1]+1)%5];
c2 = keymat[posb[0]][(posb[1]+1)%5];
frag = (""+c1+c2+"");
}
else if(posa[1] == posb[1]){
c1 = keymat[(posa[0]+1)%5][posa[1]];
c2 = keymat[(posb[0]+1)%5][posb[1]];
frag = (""+c1+c2+"");
}
else{
c1 =keymat[posb[0]][posa[1]];
c2 =keymat[posa[0]][posb[1]];
frag = (""+c1+c2+"");
}

6
return frag;
}

private static String decrypt(char c1, char c2) {


int[] posa = new int[2];
int[] posb = new int[2];
String frag = "";
posa = search(c1);
posb = search(c2);
if(posa[0] ==posb[0]){
c1 = keymat[posa[0]][(posa[1]-1)%5];
c2 = keymat[posb[0]][(posb[1]-1)%5];
frag = (""+c1+c2+"");
}
else if(posa[1] == posb[1]){
c1 = keymat[(posa[0]-1)%5][posa[1]];
c2 = keymat[(posb[0]-1)%5][posb[1]];
frag = (""+c1+c2+"");
}
else{
c1 =keymat[posb[0]][posa[1]];
c2 =keymat[posa[0]][posb[1]];
frag = (""+c1+c2+"");
}
return frag;
}

private static int[] search(char c) {


int i,j;
int[] pos = new int[2];
for (i = 0; i< 5; i++) {
for (j = 0; j < 5; j++) {
if (keymat[i][j] == c){
pos[0] = i;
pos[1] = j;
break;
}
}
}
return pos;
}}

7
OUTPUT:

ENCRYPTION:

DECRYPTION:

RESULT:

The Playfair cipher was implemented using Java.

8
Ex.No:3 IMPLEMENTATION OF HILLCIPHER
Date:22/07/2020

AIM:
Write a Java program to perform encryption and decryption using Hill Cipher.
ALGORITHM:

STEP1: Construct a key matrix of size n x n such that the plaintext will then be enciphered in
blocks of size n.In following example keymatrix is a 3 x 3 matrix and the message will be
enciphered in blocks of 3 characters.

Key Matrix: A = 121

232

221

STEP 2: Read the Message “ PAY MORE MONEY” AND Encipher the message in blocks of 3
characters

STEP 3:The first three letters of the plaintext are represented by vector

C=KP mod 26

1 2 1 e
C =2 3 2 a mod 26
2 2 1 y

STEP 4:.This step is repeated for the entire plaintext. If there are not enough letters to form
blocks of 3, pad the message with some letter, say x.

STEP 5: Display the enciphered message.

STEP 6:Find the inverse of the keymatrix and multiply the inverse of the key by each pair of
ciphertext letters (mod 26) to recover the original text.

STEP 7:Plaintext is recovered by using the decryption formula.. P=K—1C mod 26

9
PROGRAM:

import javax.swing.JOptionPane;
public class HillCipher1 {
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)
{
String text,outtext ="";
int ch, n;
ch = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter 1 to Encrypt and 2to
Decrypt!"));
text = JOptionPane.showInputDialog(null, "Enter plain/cipher text to encrypt?");
text = text.toUpperCase();
text =text.replaceAll("\\s","");
n = text.length() % 3;
if(n!=0){
for(int i = 1; i<= (3-n);i++){
text+= 'X';
}
}
System.out.println("Padded Text:" + text);

10
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));

11
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;
}
}

OUTPUT:

RESULT:

The Hill cipher was implemented using Java.

12
EX.NO:4 IMPLEMENTATION OF VIGENERECIPHER

Date:29/07/2020

AIM:
Write a Java program to perform encryption and decryption using Vigenere Cipher.

ALGORITHM:

STEP 1:Construct the Vigenère cipher which uses a 26×26 table with A to Z as the row heading
and column heading. The first row of this table has the 26 English letters. Starting with the
second row, each row has the letters shifted to the left one position in a cyclic way. For example,
when B is shifted to the first position on the second row, the letter A moves to theend.
STEP 2: The Vigenère cipher also requires a keyword, which is repeated so that the total length
is equal to that of the plaintext. For example, suppose the plaintext is MICHIGAN
TECHNOLOGICAL UNIVERSITY and the keyword is HOUGHTON. Then, the keyword must
be repeated as follows:
Plaintext:MICHIGAN TECHNOLOGICAL UNIVERSITY
Keyword: HOUGHTON HOUGHTONHOUGHTONHOUGNTO

STEP 3:To encrypt, pick a letter in the plaintext and its corresponding letter in the keyword, use
the keyword letter and the plaintext letter as the row index and column index, respectively, and
the entry at the row-column intersection is the letter in the ciphertext. For example, the first letter
in the plaintext is M and its corresponding keyword letter is H. This means that the row of H and
the column of M are used, and the entry T at the intersection is the encrypted result.

STEP 4: Repeating this process until all plaintext letters are processed.
STEP 5:To decrypt, pick a letter in the ciphertext and its corresponding letter in the keyword, use
the keyword letter to find the corresponding row, and the letter heading of the column that
contains the ciphertext letter is the needed plaintext letter. For example, to decrypt the first
letter T in the ciphertext, we find the corresponding letter H in the keyword. Then, the row ofH is
used to find the corresponding letter T and the column that contains T provides the plaintext
letter M (see the above figures). Consider the fifth letter P in the ciphertext. This letter
corresponds to the keyword letter H and row H is used to find P. Since P is on column I, the
corresponding plaintext letter isI.

13
PROGRAM:
public class VigenereCipher1 {

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

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

14
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 = "ATTACKATDAWN";
String key = "CAT";
String enciphered = encipher(text, key);
System.out.println("Encrypted message:"+enciphered);
System.out.println("Original message recovered:"+decipher(enciphered, key));

}
}
OUTPUT:

RESULT:
Thus the java program to perform encryption and decryption using Vigenere Cipher as been
implemented and the output verified successfully

15
EX.NO:5 IMPLEMENTATION OF RAIL FENCECIPHER
Date:08/08/2020

AIM:
Write a Java program to perform encryption and decryption using RailFence- Cipher

DESCRIPTION:
Rail fence Technique involves writing plain text as sequence of diagonals and then reading it
row-by-row to produce cipher text.
ALGORITHM:
STEP1: Write down the plain text message as a sequence ofdiagonals.
STEP2: Read the plain text written in Step 1 as a sequence ofrows.
Example:Original plain text message : Come home tomorrow
Arrange the plain text message as sequence of diagonals of depth 2.

STEP 3:Read the message off row by row which gives the ciphetext.

PROGRAM:
public class railfence {
public static void main(String args[])
{
String input = “inputstring”;
String output = “”;
int len = input.length(),flag = 0;
System.out.println(“Input String : ” + input);
for(int i=0;i<len;i+=2) {
output +=input.charAt(i);
}
for(int i=1;i<len;i+=2) {
output +=input.charAt(i);

16
}
System.out.println(“Ciphered Text : “+output);
}
}

OUTPUT:

RESULT:

Thus the java program for Rail Fence Transposition Technique has been implemented and the
output verified successfully.

17
EX.NO:6 IMPLEMENTATION OF ROW AND COLUMNTRANSFORMATION
CIPER
Date:12/08/2020

AIM:
To implement a program for encryption and decryption by using row and column transformation
technique.

ALGORITHM:
1. Consider the plain text hello world, and let us apply the simple columnar transposition
technique as shownbelow

H e l l
O w o r
L d

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

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

18
for (int j = 0; j < col; j++) {
if (l < k) {
ch[i][j] = s.charAt(l);
l++;
} else {
ch[i][j] = '#';
}
}
}

char trans[][] = new char[col][row];


for (int i = 0; i< row; i++) {
for (int j = 0; j < col; j++) {
trans[j][i] = ch[i][j];
}
}
for (int i = 0; i< col; i++) {
for (int j = 0; j < row; j++) {
System.out.print(trans[i][j]);
}
}

System.out.println();
}
}

OUTPUT:
Enter the plain text
Security Lab
SecurityLabSreictu
y

RESULT:
Thus the java program for Row and Column Transposition Technique has been implemented and
the output verified successfully.

19
EX.NO:7 IMPLEMENTATION OF DATA ENCRYPTION STANDARD

DATE:26/08/2020

AIM:

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

ALGORITHM:
1. Create a DESKey.
2. Create a Cipher instance from Cipher class, specify the following information andseparated
by a slash(/).
a. Algorithmname
b. Mode(optional)
c. Padding scheme (optional)
3. Convert String into Byte[] arrayformat.
4. Make Cipher in encrypt mode, and encrypt it with Cipher.doFinal()method.
5. Make Cipher in decrypt mode, and decrypt it with Cipher.doFinal()method.

PROGRAM:
DES.java
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
importjavax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
public class DES
{
public static void main(String[] argv) {
try{
System.out.println("Message Encryption UsingDESAlgorithm\n ------- ");
KeyGeneratorkeygenerator = KeyGenerator.getInstance("DES");
SecretKeymyDesKey = keygenerator.generateKey();
Cipher desCipher;
desCipher =Cipher.getInstance("DES/ECB/PKCS5Padding");
desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
byte[] text = "Secret Information ".getBytes();
System.out.println("Message [Byte Format] : " + text);
System.out.println("Message : " + newString(text));
byte[] textEncrypted = desCipher.doFinal(text);
System.out.println("Encrypted Message: " + textEncrypted);
desCipher.init(Cipher.DECRYPT_MODE, myDesKey);
byte[] textDecrypted =desCipher.doFinal(textEncrypted);

20
System.out.println("Decrypted Message: " + new String(textDecrypted));
}catch(NoSuchAlgorithmExceptione){
e.printStackTrace();
}catch(NoSuchPaddingExceptione){
e.printStackTrace();
}catch(InvalidKeyExceptione){
e.printStackTrace();
}catch(IllegalBlockSizeExceptione){
e.printStackTrace();
}catch(BadPaddingExceptione){
e.printStackTrace();
}
}
}
OUTPUT:
Message Encryption Using DES Algorithm

Message [Byte Format] :[B@4dcbadb4


Message : Secret Information
Encrypted Message: [B@504bae78
Decrypted Message: SecretInformation

RESULT:
Thus the java program for DES Algorithm has been implemented and the output verified
successfully.

21
EX.NO:8 IMPLEMENTATION OF ADVANCED ENCRYPTION STANDARD

DATE: 02/09/2020

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

ALGORITHM:
1. AES is based on a design principle known as asubstitution–permutation.
2. AES does not use a Feistel network like DES, it uses variant ofRijndael.
3. It has a fixed block size of 128 bits, and a key size of 128, 192, or 256bits.
4. AES operates on a 4 × 4 column-major order array of bytes, termed the state

PROGRAM:
AES.java
AES.java
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 SecretKeySpecsecretKey;
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();

22
}
}

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 = "annaUniversity";

String originalString = "www.annauniv.edu";


String encryptedString = AES.encrypt(originalString, secretKey);
String decryptedString = AES.decrypt(encryptedString, secretKey);

23
System.out.println("URL Encryption UsingAESAlgorithm\n -------------");
System.out.println("Original URL : " + originalString);
System.out.println("Encrypted URL : " + encryptedString);
System.out.println("Decrypted URL : " + decryptedString);
}
}

OUTPUT:
URL Encryption Using AES Algorithm

Original URL : www.annauniv.edu


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

RESULT:
Thusthe java program for AES Algorithm has been implemented for URL Encryption and the
output verified successfully

24
EX.NO:9 IMPLEMENTATION OF RIVEST SHAMIR ADLEMAN ALGORITHM

DATE:09/09/2020

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

ALGORITHM:
1. Choose two prime number p andq
2. Compute the value of n andp
3. Find the value of e (publickey)
4. Compute the value of d (private key) using gcd()
5. Do the encryption anddecryption
a. Encryption is givenas,
c = te mod n
b. Decryption is givenas,
t = cd mod n

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>

25
<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) {

26
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 the RSA algorithm has been implemented using HTML & CSS and the output has been
verified successfully.

27
EX:NO:10 IMPLEMENTATION OF DIFFIE-HELLMAN KEY EXCHANGE

DATE:16/09/2020

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

ALGORITHM:

1. Enter the value of q, a prime number and α, a primitive root ofq.


2. Choose XA<q andXB<q.
3. Calculate YA=αXA mod q and YB=αXBmod q.
4. Calculate Secret Key K at user A as (YB) XA modq.
5. Calculate Secret Key K at user B as (YA) XBmod q.
6. Display the shared secretkey.
PROGRAM:

import java.util.*;
class DiffieHellman
{
public static void main(String args[])
{
Scanner ob=newScanner(System.in);
System.out.println("Enter p=");
int p = ob.nextInt(); /* publicly known (prime number)*/
System.out.println("Enter g =");
int g = ob.nextInt(); /* publicly known (primitive root) */
System.out.println("Enter Alice private key X =");
int x = ob.nextInt(); /* only Alice knows this secret */
System.out.println("Enter Bob private key y =");
int y = ob.nextInt(); /* only Bob knows this secret */
double aliceSends = (Math.pow(g, x)) % p; // Alice's Public Key
double bobComputes = (Math.pow(aliceSends, y)) % p;//Bob's Secret Key
double bobSends = (Math.pow(g, y)) % p;//Bob's Public Key
double aliceComputes = (Math.pow(bobSends, x)) % p;//Alice's
double sharedSecret = (Math.pow(g, (x * y))) % p;
System.out.println("simulation of Diffie-Hellman key exchange algorithm\n----------------------------
");
System.out.println("Alice Sends(Public Key) : " + aliceSends);
System.out.println("Bob Computes(Secret key : " + bobComputes);

28
System.out.println("Bob Sends(Public Key) : " + bobSends);
System.out.println("Alice Computes(Secret Key) : " + aliceComputes);
System.out.println("Shared Secret : " + sharedSecret);
/* shared secrets should match and equality is transitive */
if ((aliceComputes == sharedSecret) && (aliceComputes ==bobComputes))
System.out.println("Success: Shared Secrets Matches! " + sharedSecret);
else
System.out.println("Error: Shared Secrets does not Match");}
}

OUTPUT:

simulation of Diffie-Hellman key exchange algorithm

Alice Sends : 4.0


Bob Computes : 18.0
Bob Sends :10.0
Alice Computes : 18.0
Shared Secret : 18.0
Success: Shared Secrets Matches! 18.0

RESULT:
Thus the Diffie-Hellman key exchange algorithm has been implemented using Java Program and
the output has been verified successfully.

29
EX.NO:11 IMPLEMENTATION OF SECURE HASHALGORITHM-1

DATE:28/10/20

AIM:
To Calculate the message digest of a text using the SHA-1 algorithm.

ALGORITHM:
1. Append PaddingBits
2. Append Length - 64 bits are appended to theend
3. Prepare ProcessingFunctions
4. Prepare ProcessingConstants
5. InitializeBuffers
6. Processing Message in 512-bit blocks (L blocks in totalmessage)

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

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

OUTPUT:
Message digest object info:

Algorithm=SHA1
Provider=SUN version 12
ToString=SHA1 Message Digest from SUN, <initialized>
SHA1("")=DA39A3EE5E6B4B0D3255BFEF95601890AFD80709
SHA1("abc")=A9993E364706816ABA3E25717850C26C9CD0D89D
SHA1("abcdefghijklmnopqrstuvwxyz")=32D10C7B8CF96570CA04CE37F2A19D84240D3A89

RESULT:
Thus the Secure Hash Algorithm (SHA-1) has been implemented and the output has been verified
successfully.

31
EX.NO:12 IMPLEMENTATION OF DIGITAL SIGNATURESTANDARD

DATE:31/10/2020

AIM:
To implement the SIGNATURE SCHEME - Digital Signature Standard.

ALGORITHM:
1. Create a KeyPairGeneratorobject.
2. Initialize the KeyPairGeneratorobject.
3. Generate the KeyPairGenerator....
4. Get the private key from thepair.
5. Create a signature object.
6. Initialize the Signatureobject.
7. Add data to the Signatureobject
8. Calculate theSignature

PROGRAM:
import java.security.KeyPair;
importjava.security.KeyPairGenerator;
import java.security.PrivateKey;
importjava.security.Signature;
import java.util.Scanner;
public class CreatingDigitalSignature {
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner(System.in);
System.out.println("Enter some text");
String msg = sc.nextLine();
KeyPairGeneratorkeyPairGen = KeyPairGenerator.getInstance("DSA");
keyPairGen.initialize(2048);
KeyPair pair = keyPairGen.generateKeyPair();
PrivateKeyprivKey = pair.getPrivate();
Signature sign = Signature.getInstance("SHA256withDSA"); sign.initSign(privKey);
byte[] bytes = "msg".getBytes();
sign.update(bytes);
byte[] signature = sign.sign();
System.out.println("Digital signature for given text: "+new String(signature, "UTF8"));
}
}
OUTPUT:
Enter some text
Hi how are you
Digital signature for given text: 0=@gRD???-?.???? /yGL?i??a!?

RESULT:
Thus the Digital Signature Standard Signature Scheme has been implemented and the output has
been verified successfully.

32
EX.NO:13 DEMONSTRATION OF INTRUSION DETECTION SYSTEM

DATE:04/11/2020

AIM:
To demonstrate Intrusion Detection System (IDS) using Snort software tool.
STEPS ON CONFIGURING AND INTRUSION DETECTION:
1. Download Snort from the Snort.org website.(http://www.snort.org/snort-downloads)
2. Download Rules(https://www.snort.org/snort-rules). You must register to get the rules.(You
should download theseoften)
3. Double click on the .exe to install snort. This will install snort in the “C:\Snort” folder.It is
important to have WinPcap (https://www.winpcap.org/install/)installed
4. Extract the Rules file. You will need WinRAR for the .gzfile.
5. Copy all files from the “rules” folder of the extracted folder. Now paste the rulesinto
“C:\Snort\rules” folder.
6. Copy “snort.conf” file from the “etc” folder of the extracted folder. You must paste it into
“C:\Snort\etc” folder. Overwrite any existing file. Remember if you modify your snort.conf fileand
download a new file, you must modify it for Snort towork.
7. Open a command prompt (cmd.exe) and navigate to folder “C:\Snort\bin” folder. ( at the Prompt,
type cd\snort\bin)
8. To start (execute) snort in sniffer mode use followingcommand:
snort -dev -i 3
-i indicates the interface number. You must pick the correct interface number. In my case, it is 3.
-dev is used to run snort to capture packets on your network.
To check the interface list, use following command:
snort -W

33
Finding an interface
You can tell which interface to use by looking at the Index number and finding Microsoft. As you
can see in the above example, the other interfaces are for VMWare. My interface is 3.
9. To run snort in IDS mode, you will need to configure the file “snort.conf” according toyour
networkenvironment.
10. To specify the network address that you want to protect in snort.conf file, look for the following
line.
var HOME_NET 192.168.1.0/24 (You will normally see any here)
11. You may also want to set the addresses of DNS_SERVERS, if you have some on yournetwork.
Example:
example snort
12. Change the RULE_PATH variable to the path of rulesfolder.
var RULE_PATHc:\snort\rules
path to rules
13. Change the path of all library files with the name and path on your system. and you must
change the path ofsnort_dynamicpreprocessorvariable.

34
C:\Snort\lib\snort_dynamiccpreprocessor
You need to do this to all library files in the “C:\Snort\lib” folder. The old path might be:
“/usr/local/lib/…”. you will need to replace that path with your system path. Using C:\Snort\lib
14. Change the path of the “dynamicengine” variable value in the “snort.conf” file..
Example:
dynamicengine C:\Snort\lib\snort_dynamicengine\sf_engine.dll
15 Add the paths for “include classification.config” and “include reference.config” files.
include c:\snort\etc\classification.config
include c:\snort\etc\reference.config
16. Remove the comment (#) on the line to allow ICMP rules, if it is commented with a#.
include$RULE_PATH/icmp.rules
17. You can also remove the comment of ICMP-info rules comment, if it iscommented.
include$RULE_PATH/icmp-info.rules
18. To add log files to store alerts generated by snort, search for the “output log” test insnort.conf
and add the following line:
output alert_fast: snort-alerts.ids
19. Comment (add a #) the whitelist $WHITE_LIST_PATH/white_list.rules and the blacklist
Change the nested_ipinner , \ to nested_ip inner #,\
20. Comment out (#) followinglines:
#preprocessornormalize_ip4
#preprocessor normalize_tcp: ipsecnstream
#preprocessor normalize_icmp4
#preprocessor normalize_ip6
#preprocessor normalize_icmp6
21. Save the “snort.conf”file.
22. To start snort in IDS mode, run the followingcommand:
snort -c c:\snort\etc\snort.conf -l c:\snort\log -i 3
(Note: 3 is used for my interface card)
If a log is created, select the appropriate program to open it. You can use WordPard or NotePad++
to read the file.

35
To generate Log files in ASCII mode, you can use following command while running snort in IDS
mode:
snort -A console -i3 -c c:\Snort\etc\snort.conf -l c:\Snort\log -K ascii
23. Scan the computer that is running snort from another computer by using PING orNMap
(ZenMap).
After scanning or during the scan you can check the snort-alerts.ids file in the log folder to insure it
is logging properly. You will see IP address folders appear.

Snort monitoring traffic –

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

36
EX.NO:14 EXPLORATION OF N-STALKER -VULNERABILITY

DATE:07/11/2020 ASSESSMENTTOOL

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

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

1. Start N-Stalker from a Windows computer. The program is installed under Start➪
Programs ➪N-Stalker ➪N-Stalker Free Edition.
2. Enter a host address or a range of addresses toscan.
3. Click StartScan.
4. After the scan completes, the N-Stalker Report Manager willprompt

5. you to select a format for the resulting report as choose GenerateHTML.


6. Review the HTML report for vulnerabilities.

37
HARSHINI K
311517205014

Now goto “Scan Session”, enter the target URL.


In scan policy, you can select from the four options,

Manual test which will crawl the website and will be waiting for manual attacks.
full xss assessment
owasp policy
Web server infrastructure analysis.
Once, the option has been selected, next step is “Optimize settings” which will crawl the
whole website for further analysis.

In review option, you can get all the information like host information,
technologies used, policy name, etc.

38
39
Once done, start the session and start the scan.

The scanner will crawl the whole website and will show the scripts, broken pages, hidden
fields, information leakage, web forms related information which helps to analyzefurther.

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

RESULT:

Thus the N-Stalker Vulnerability Assessment tool has been downloaded, installed
and the features has been explored by using a vulnerable website.

41
EX.NO:15 DEFEATING MALWARE - BUILDINGTROJANS

DATE:11/11/2020

AIM:

To build a Trojan and know the harmness of the trojan malwares in a


computer system.

PROCEDURE:
1. Create a simple trojan by using Windows Batch File(.bat)
2. Type these below code in notepad and save it asTrojan.bat
3. Double click on Trojan.batfile.
4. When the trojan code executes, it will open MS-Paint, Notepad, Command Prompt,
Explorer, etc.,infinitely.
5. Restart the computer to stop the execution of thistrojan.

TROJAN:

In computing, a Trojan horse,or trojan, is any malware which misleads users of its
true intent.

Trojans are generally spread by some form of social engineering, for example where a
user is duped into executing an email attachment disguised to appear not suspicious,
(e.g., a routine form to be filled in), or by clicking on some fake advertisement on
social media or anywhere else.

Although their payload can be anything, many modern forms act as abackdoor,
contacting a controller which can then have unauthorized access to the affected
computer.
Trojans may allow an attacker to access users' personal information such as banking
information, passwords, or personal identity.

Example: Ransomware attacks are often carried out using a trojan.

42
CODE:
Trojan.bat

@echo off //@echo off // It instructs to hide the commands when batch files isexecuted

:x //loop variable

start
winwordstart
mspaint

startnotepad

start cmd
start explorer
start control
start calc
goto x

OUTPUT
(MS-Paint, Notepad, Command Prompt, Explorer will open infinitely)

RESULT:
Thus a trojan has been built and the harmness of the trojan viruses has been explored.

43
EX.NO:16 DEFEATING MALWARE - ROOTKITHUNTER

DATE:11/11/2020
AIM:
To install a rootkit hunter and find the malwares in a computer.

ROOTKIT HUNTER:
rkhunter (Rootkit Hunter) is a Unix-based tool that scans for rootkits,
backdoors and possible local exploits.
It does this by comparing SHA-1 hashes of important files with known good ones
in online databases, searching for default directories (of rootkits), wrong permissions,
hidden files, suspicious strings in kernel modules, and special tests for Linux and
FreeBSD.
rkhunter is notable due to its inclusion in popular operating systems (Fedora,
Debian, etc.)
The tool has been written in Bourne shell, to allow for portability. It can run on
almost all UNIX-derived systems.
GMER ROOTKIT TOOL:
GMER is a software tool written by a Polish researcher
PrzemysławGmerek, for detecting and removing rootkits.
It runs on Microsoft Windows and has support for Windows NT, 2000, XP, Vista,
7, 8 and 10. With version 2.0.18327 full support for Windows x64 is added.
Step 1

44
Visit GMER's website (see Resources) and download the GMER executable.

Click the "Download EXE" button to download the program with a random file name, as some
rootkits will close “gmer.exe” before you can open it.

Step 2

45
Double-click the icon for the program.

Click the "Scan" button in the lower-right corner of the dialog box. Allow the program to
scan your entire hard drive.

Step 3

When the program completes its scan, select any program or file listed in red. Right-click it
and select "Delete."

46
If the red item is a service, it may be protected. Right-click the service and select "Disable."
Reboot your computer and run the scan again, this time selecting "Delete" when that service is
detected.

When your computer is free of Rootkits, close the program and restart your PC.

RESULT:
In this experiment a rootkit hunter software tool has been installed and the rootkits have
been detected.

47

You might also like