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

Java Implementation of Ciphers

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)
11 views44 pages

Java Implementation of Ciphers

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

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 [Link];

public class CaesarCipher {


private static String encrypt(String txt, int k) {
StringBuilder res = new StringBuilder();
for (int i = 0; i < [Link](); i++) {
char ch = [Link](i);
if ([Link](ch)) {
ch = (char)(((ch + k - 65) % 26 + 26) % 26 + 65);
} else if ([Link](ch)) {
ch = (char)(((ch + k - 97) % 26 + 26) % 26 + 97);
}
[Link](ch);
}
return [Link]();
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
[Link]("Enter the plain text: ");
String plainText = [Link]();
[Link]("Enter the key: ");
1
int key = [Link]();
String cipherText = encrypt(plainText, key);
String pText = encrypt(cipherText, 26 - (key % 26));

[Link]("Cipher Text = " + cipherText);


[Link]("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 [Link].*;

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 < [Link]();) {
StringBuffer temp = new StringBuffer();
[Link]([Link](i));

if ((i + 1) < [Link]()) {


if ([Link](i) != [Link](i + 1)) {
[Link]([Link](i + 1));
String t = [Link]();
[Link](t);
i = i + 2;
} else {
[Link]('x');
String t = [Link]();
[Link](t);
i++;
}
} else {
[Link]('z');
String t = [Link]();
[Link](t);
i++;
}
}
return dg;
}

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


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

for (int i = 0; i < [Link](); i++) {


if (![Link]([Link](i))) {
[Link](counter, [Link](i));
[Link]([Link](i), counter);
counter++;
}
}

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


if (i == 'j' || [Link](i)) continue;
[Link](counter, i);
[Link](i, counter);
counter++;
}

int x = 0, y = 0;
for (int i = 0; i < 25; i++) {
char ch = [Link](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 = [Link](0), b = [Link](1);
int[] aCrd = new int[2];
int[] bCrd = new int[2];
int place1 = [Link](a);
int place2 = [Link](b);

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

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

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


[Link]();
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++)
[Link](mat[i][j] + " ");
[Link]();
}
[Link]();
}

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


List<String> enc = new ArrayList<>();
for (int i = 0; i < [Link](); i++) {
String curStr = [Link](i);
char a = [Link](0), b = [Link](1);
int[] aCrd = new int[2];
int[] bCrd = new int[2];
int place1 = [Link](a);
int place2 = [Link](b);

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

char orient = [Link](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;
}
[Link]("" + 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) {
[Link](str);
}
return [Link]();
}

public static void main(String[] args) {


PlayFair pf = new PlayFair();
Scanner sc = new Scanner([Link]);
[Link]("Enter the plaintext: ");
String pText = [Link]().toLowerCase().replaceAll("[^a-z]", "");
[Link]("Enter the key: ");
String key = [Link]().toLowerCase().replaceAll("[^a-z]", "");
String cipherText = [Link](pText, key);
[Link]("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 = ([Link]() % 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
[Link] 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 [Link];

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++) {
[Link](counter, i);
[Link](i, counter);
counter++;
}
}
private void print(int k) {
if (k == 1) {
[Link]();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
[Link](kyMtrx[i][j] + "\t");
}
8
[Link]();
}
[Link]();
}
}
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 = [Link](ctr);
int temp = [Link](ch);
kyMtrx[i][j] = temp;
ctr++;
}
}
}
private void cnvtPtVec(String pt) {
int ctr = 0;
ptVector = new int[[Link]() / n][n];
for (int i = 0; i < [Link]() / n; i++) {
for (int j = 0; j < n; j++) {
int ch = [Link]([Link](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 = [Link](encMat[i][j]);
[Link](ch);
9
}
}
return [Link]();
}
public String encrypt(String plainText, String k) {
init();
n = ([Link]() == 4) ? 2 : 3;
GenKyMtrx(k);
print(1);
cnvtPtVec(plainText);
cnvtCipher([Link]());
return cnvtStr([Link]());
}
}

public class lav {


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

plainText = [Link]();
key = [Link]();

[Link]("Plain Text: " + plainText);


[Link]("Key: " + key);

hill cipher = new hill();


String cipherText = [Link](plainText, key);
[Link]("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 [Link] < [Link]:
4. key += [Link](ctr)
5. If ctr++ == [Link]: 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)(([Link](i) - [Link](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 += [Link](ctr);
ctr = (ctr + 1 == [Link]()) ? 0 : ctr + 1;
}
return key;
}
private String cipher(String k, String pt) {
String enc = "";
for (int i = 0; i < [Link](); i++) {
enc += (char) ((([Link](i) + [Link](i)) % 26) + 'A');
}
return enc;
}
private String decipher(String k, String ct) {
String dTxt = "";
for (int i = 0; i < [Link](); i++) {
dTxt += (char) (([Link](i) - [Link](i) + 26) % 26 + 'A');
}
return dTxt;
}
public String encrypt(String pt, String k) {
12
String key = equity([Link](), k);
String res = cipher(key, pt);
return res;
}
public String decrypt(String ct, String k) {
String key = equity([Link](), k);
String res = decipher(key, ct);
return res;
}
}

public class vigenereCipher {

public static void main(String[] args) {


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

plainText = [Link]();
key = [Link]();

[Link]("Plain Text : " + plainText);


[Link]("Key : " + key);

vigenere cipher = new vigenere();


String cipherText = [Link](plainText, key);
String pText = [Link](cipherText, key);

[Link]("\nCipher Text = " + cipherText);


[Link]("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 < [Link](); i++) {
crypt[j][i] = [Link](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')
[Link](crypt[i][j]);
return [Link]();
}
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] = [Link](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') {
[Link](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 [Link]();
}

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


for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
[Link](arr[i][j] + " ");
}
[Link]();
}
}
public String encrypt(String pt, int k) {
String res = "";
m = k;
n = [Link]();
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 = [Link]();
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;

[Link]("Plain Text: " + plainText);


[Link]("Key: " + key);

railFence cipher = new railFence();


String cipherText = [Link](plainText, key);
String pText = [Link](cipherText, key);
16
[Link]("\nCipher Text = " + cipherText);
[Link]("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 [Link];

class TransCipher {
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the plain text:");
String pl = [Link]();
[Link]();
String s = "";
int start = 0;
for (int i = 0; i < [Link](); i++) {
if ([Link](i) == ' ') {
s = s + [Link](start, i);
start = i + 1;
}
}
s = s + [Link](start);
[Link]("Plain text without spaces: " + s);
int k = [Link]();
int col = 4;
int row = (int) [Link]((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] = [Link](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];
}
}
[Link]("Transposed Cipher Text:");
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++) {
[Link](trans[i][j]);
}
}
[Link]();
}
}

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 [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class DES {


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

[Link]("Message [Byte Format] : " + new String(text));


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

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 [Link];
import [Link];
import [Link];
import [Link];
import [Link].Base64;

import [Link];
import [Link];

public class Main {

private static SecretKeySpec secretKey;


private static byte[] key;

public static void setKey(String myKey) {


try {
key = [Link]("UTF-8");
MessageDigest sha = [Link]("SHA-1");
key = [Link](key);
key = [Link](key, 16);
secretKey = new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
[Link]();
}
}

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


try {
setKey(secret);
Cipher cipher = [Link]("AES/ECB/PKCS5Padding");
[Link](Cipher.ENCRYPT_MODE, secretKey);
return [Link]().encodeToString([Link]([Link]("UTF-8")));
} catch (Exception e) {
[Link]("Error while encrypting: " + [Link]());
22
}
return null;
}

public static String decrypt(String strToDecrypt, String secret) {


try {
setKey(secret);
Cipher cipher = [Link]("AES/ECB/PKCS5Padding");
[Link](Cipher.DECRYPT_MODE, secretKey);
return new String([Link]([Link]().decode(strToDecrypt)));
} catch (Exception e) {
[Link]("Error while decrypting: " + [Link]());
}
return null;
}

public static void main(String[] args) {


final String secretKey = "cryptography";
String originalString = "[Link]";
String encryptedString = [Link](originalString, secretKey);
String decryptedString = [Link](encryptedString, secretKey);
[Link]("Original String: " + originalString);
[Link]("Encrypted String: " + encryptedString);
[Link]("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 = [Link]('p').value;
q = [Link]('q').value;
no = [Link]('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 = [Link](no, e).toFixed(0);
ct = ctt % n;

25
dtt = [Link](ct, d).toFixed(0);
dt = dtt % n;
[Link]('publickey').innerHTML = n;
[Link]('exponent').innerHTML = e;
[Link]('privatekey').innerHTML = d;
[Link]('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 [Link];

public class DiffieHellman {


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

// Private keys for Alice and Bob


BigInteger x = [Link](4); // Alice's private key
BigInteger y = [Link](3); // Bob's private key

// Alice computes her public value


BigInteger aliceSends = [Link](x, p);
// Bob computes the shared secret using Alice's public value
BigInteger bobComputes = [Link](y, p);

// Bob computes his public value


BigInteger bobSends = [Link](y, p);
// Alice computes the shared secret using Bob's public value
BigInteger aliceComputes = [Link](x, p);

// Display results
[Link]("Simulation of Diffie-Hellman Key Exchange Algorithm\n");
[Link]("Alice Sends: " + aliceSends);
[Link]("Bob Computes: " + bobComputes);
[Link]("Bob Sends: " + bobSends);
[Link]("Alice Computes: " + aliceComputes);

// Verify if the shared secrets match


27
if ([Link](bobComputes)) {
[Link]("Success: Shared Secrets Match! " + bobComputes);
} else {
[Link]("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 [Link].*;

public class SHA1Hashing {


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

[Link]("Message digest object info:\n");


[Link]("Algorithm = " + [Link]());
[Link]("Provider = " + [Link]());
[Link]("ToString = " + [Link]());

// First input: an empty string


String input = "";
[Link]([Link]());
byte[] output = [Link]();
[Link]("\nSHA1(\"" + input + "\") = " + bytesToHex(output));

// Second input: "abc"


input = "abc";
[Link]([Link]());
output = [Link]();
[Link]("\nSHA1(\"" + input + "\") = " + bytesToHex(output));

// Third input: "abcdefghijklmnopqrstuvwxyz"


input = "abcdefghijklmnopqrstuvwxyz";
[Link]([Link]());
output = [Link]();
[Link]("\nSHA1(\"" + input + "\") = " + bytesToHex(output));

} catch (Exception e) {
[Link]("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) {
[Link](hexDigit[(aB >> 4) & 0x0f]); // Get high nibble
[Link](hexDigit[aB & 0x0f]); // Get low nibble
}
return [Link]();
}
}

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 [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class CreatingDigitalSignature {


public static void main(String args[]) throws Exception {
// Get user input
Scanner sc = new Scanner([Link]);
[Link]("Enter some text");
String msg = [Link]();

// Generate a key pair using DSA


KeyPairGenerator keyPairGen = [Link]("DSA");
[Link](2048);
KeyPair pair = [Link]();

// Get the private key from the generated pair


PrivateKey privKey = [Link]();

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


Signature sign = [Link]("SHA256withDSA");
[Link](privKey);

// Convert the message to bytes


byte[] bytes = [Link](StandardCharsets.UTF_8);
[Link](bytes);

// Generate the digital signature


byte[] signature = [Link]();

// Print the generated digital signature


32
[Link]("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 [Link] website. ([Link]
2. Download Rules([Link] 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” [Link] is important to
have WinPcap ([Link] 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 “[Link]” 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 [Link] file and
download a new file, you must modify it for Snort to work.
7. Open a command prompt ([Link]) 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 “[Link]” according to your
network environment.
10. To specify the network address that you want to protect in [Link] file, look for the following
line. var HOME_NET [Link]/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 “[Link]”
file.. Example:
dynamicengine C:\Snort\lib\snort_dynamicengine\sf_engine.dll

15. Add the paths for “include [Link]” and “include [Link]”
files. include c:\snort\etc\[Link]
include c:\snort\etc\[Link]

16. Remove the comment (#) on the line to allow ICMP rules, if it is commented with a
#. include $RULE_PATH/[Link]

17. You can also remove the comment of ICMP-info rules comment, if it is commented.
include $RULE_PATH/[Link]

18. To add log files to store alerts generated by snort, search for the “output log” test in [Link] and
add the following line:
output alert_fast: [Link]

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 “[Link]” file.

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


35
snort -c c:\snort\etc\[Link] -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\[Link] -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 [Link] 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 [Link].
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 [Link]
3. Double click on [Link] 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:
[Link]
@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 “[Link]” 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

Common questions

Powered by AI

The Playfair cipher algorithm processes plaintext by converting it into digraphs (pairs of characters). If two characters are the same or only one character remains, a filler letter like 'X' is added to form a digraph. A key matrix is then constructed by inserting characters from an initial keyword into a 5x5 grid, avoiding duplicates and combining I and J into a single cell. Letters not in the keyword are filled in the remaining spaces of the grid. The digraphs are then encrypted by their positions in the matrix, operating on the rules based on their alignments in rows, columns, or diagonally .

Rootkit Hunter (rkhunter) is a Unix-based tool that scans for rootkits by checking SHA-1 hashes of files, searching for default directories, incorrect permissions, and hidden files. GMER, on the other hand, is a Windows-based tool focusing on detecting unauthorized processes and changes in system behavior related to rootkits. While rkhunter is used across Unix-derived systems and focuses on typical rootkit indicators, GMER's approach involves real-time detection and manipulation of Windows processes, making it effective in dynamic environments .

The Rail Fence Cipher in Java involves arranging the plaintext into a zigzag pattern along rows determined by the key, then constructing the ciphertext by reading sequentially in rows. For example, with plaintext 'HELLO' and key 2, it arranges into HLO and ELO, resulting in 'HLOELO'. Although easy to implement and understand, its effectiveness is low due to its susceptibility to frequency analysis and lack of key management complexity, making it less secure against modern cryptographic attacks .

The Vigenère cipher uses a repeated keyword to encrypt a message by aligning it with the plaintext. Each character in the plaintext is shifted by the character value of the corresponding keyword character. This is done using the formula ((plainText[i] + key[i]) % 26) + 'A'. This process differs from simple substitution ciphers as the Vigenère cipher uses multiple Caesar shifts based on keyword letters making it polyalphabetic, whereas simple substitution uses a fixed shift for all characters, offering greater security against frequency analysis .

The N-Stalker Vulnerability Assessment Tool can test for various web application vulnerabilities, including Cross-Site Scripting (XSS), Open Web Application Security Project (OWASP) policy issues, and web server infrastructure errors. The tool benefits web application security by providing a comprehensive analysis of potential vulnerabilities, detailed reports on severity, and actionable recommendations for mitigation. It utilizes a large database of attack signatures, which helps in identifying and addressing a wide range of security threats efficiently .

The Caesar Cipher in Java works by shifting the characters in the plaintext by a specified key value. The algorithm iterates through each character of the plaintext, checks if it is uppercase, then shifts it using the formula ((ch + k - 65) % 26 + 26) % 26 + 65 for uppercase letters, and ((ch + k - 97) % 26 + 26) % 26 + 97 for lowercase letters. This ensures a wrap-around in the alphabet. The decryption involves shifting back using 26 - (key % 26). For example, encrypting 'hello' with a key of 3 results in 'khoor', and decrypting 'khoor' with the adjusted key restores 'hello' .

Creating a basic trojan using a Windows Batch file involves writing scripts to execute multiple system commands like opening applications repeatedly, which can cause system overloads. For example, a script might include opening MS Paint, Notepad, and Command Prompt in a loop. Such malware misleads users about its true intent and can lead to system disruption by consuming resources. Trojans can be vectors for more severe attacks, like data theft or ransomware, leading to unauthorized access and potential loss of sensitive information .

The Row and Column Transposition technique offers the advantage of increased security through reordering characters rather than substitution. The algorithm in Java involves arranging the plaintext into a predefined grid format, writing the text row-wise, and then reading the column-wise to form the ciphertext. This results in a permutation of the original order of characters, making patterns harder to detect when compared to simple substitution ciphers. The technique preserves the frequency of character occurrence, maintaining the original set of characters .

In the DES algorithm, the initial permutation (IP) rearranges the bits of a 64-bit plaintext block before the main encryption process begins. This step mixes the bits to reduce patterns and organize data for subsequent processing. The final permutation (FP) reorders the bits again after the 16 rounds of encryption have been completed, adding an extra layer of security and ensuring that the output—ciphertext—is more unpredictable and resistant to attacks, thereby enhancing the overall encryption strength .

The Vigenère cipher, once considered unbreakable, significantly contributed to polyalphabetic cipher development. However, with modern computing, it is vulnerable to frequency analysis and known-plaintext attacks, limiting its utility in current cryptographic applications. Despite this, its historical significance remains as a foundation for modern encryption techniques. Current cryptographic standards like AES offer greater security, efficiency, and robustness, meeting the demands of digital communications more effectively than the Vigenère cipher .

You might also like