0% found this document useful (0 votes)
27 views17 pages

Practical3-4 (INS) Nakul

Uploaded by

Meet Panchal
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)
27 views17 pages

Practical3-4 (INS) Nakul

Uploaded by

Meet Panchal
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
You are on page 1/ 17

FACULTY OF ENGINEERING & TECHNOLOGY

Subject : Information & Network Security Laboratory


Subject Code: 203105311

B.Tech – 4th Year 7th Semester


.

Practical – 3
Aim:-A) Playfair Cipher Encryption

Theory:

• Polygraphic Cipher: The Playfair cipher is a polygraphic substitution cipher,


which encrypts pairs of letters (digraphs), rather than single letters. This makes it
harder to break compared to monoalphabetic ciphers, as it accounts for the
frequency of digraphs rather than individual letters.

• 5x5 Grid Key Square: It uses a 5x5 grid filled with letters of the alphabet
(combining 'I' and 'J' to fit all 26 letters). The grid is generated using a keyword,
with remaining letters filled in alphabetical order.

• Encryption Rules: The Playfair cipher has specific rules for encrypting digraphs:

• If both letters are the same or only one letter remains, insert a filler letter
('X').
• If the letters appear on the same row of the grid, replace them with the
letters immediately to their right (wrapping around to the beginning of the
row if necessary).
• If the letters appear in the same column, replace them with the letters
immediately below them (wrapping around to the top of the column if
necessary).
• If the letters form a rectangle, replace them with the letters on the same
row but at the other pair of corners of the rectangle.

• Security: While stronger than monoalphabetic ciphers, the Playfair cipher is still
relatively easy to break with modern cryptanalysis techniques. Its primary use is
educational, demonstrating the principles of digraph substitution.

1|Page
Nakul Lohar
210303105503
7B23
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311

B.Tech – 4th Year 7th Semester

Code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define SIZE 5

void generateKeyTable(char key[], char keyTable[SIZE][SIZE]) {


int flag[26] = {0}, i, j = 0;
for (i = 0; key[i]; i++) if (key[i] != 'j' && flag[key[i] - 'a']++ == 0)
keyTable[j / SIZE][j++ % SIZE] = key[i];
for (i = 0; i < 26; i++) if (flag[i] == 0 && (i + 'a') != 'j') keyTable[j /
SIZE][j++ % SIZE] = i + 'a';
}

void search(char keyTable[SIZE][SIZE], char a, char b, int *row1, int


*col1, int *row2, int *col2) {
int i, j;
if (a == 'j') a = 'i';
if (b == 'j') b = 'i';
for (i = 0; i < SIZE; i++) for (j = 0; j < SIZE; j++) {
if (keyTable[i][j] == a) *row1 = i, *col1 = j;
if (keyTable[i][j] == b) *row2 = i, *col2 = j;
}
}

void encrypt(char str[], char keyTable[SIZE][SIZE]) {


int i, row1, col1, row2, col2, len = strlen(str);
for (i = 0; i < len; i += 2) {
if (str[i] == str[i + 1]) memmove(&str[i + 1], &str[i], len - i), str[i + 1]
= 'x', len++;
search(keyTable, str[i], str[i + 1], &row1, &col1, &row2, &col2);
if (row1 == row2) str[i] = keyTable[row1][(col1 + 1) % SIZE], str[i +
1] = keyTable[row2][(col2 + 1) % SIZE];
else if (col1 == col2) str[i] = keyTable[(row1 + 1) % SIZE][col1], str[i +

2|Page
Nakul Lohar
210303105503
7B23
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311

B.Tech – 4th Year 7th Semester

1] = keyTable[(row2 + 1) % SIZE][col2];
else str[i] = keyTable[row1][col2], str[i + 1] = keyTable[row2][col1];
}
}

int main() {
char key[] = "keyword";
char str[] = "helloplayfaircipher";
char keyTable[SIZE][SIZE];
int i;

for (i = 0; str[i]; i++) str[i] = tolower(str[i]);

generateKeyTable(key, keyTable);
printf("Key Table:\n");
for (i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) printf("%c ", keyTable[i][j]);
printf("\n");
}

printf("Original Text: %s\n", str);


encrypt(str, keyTable);
printf("Encrypted Text: %s\n", str);

return 0;
}

3|Page
Nakul Lohar
210303105503
7B23
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311

B.Tech – 4th Year 7th Semester

Output:

4|Page
Nakul Lohar
210303105503
7B23
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311

B.Tech – 4th Year 7th Semester

Aim:-B) Playfair Cipher Decryption

Theory:-

• Digraph Decryption: The Playfair Cipher decrypts pairs of letters (digraphs) by


reversing the encryption rules. For each pair of letters in the ciphertext, the
positions of the letters in the 5x5 key square are located. Depending on their
relative positions (same row, same column, or forming a rectangle), the
decryption rules are applied to find the corresponding plaintext letters.

• Handling Special Cases: Special cases in the ciphertext, such as repeated letters
and padding (commonly 'X' added during encryption), need to be handled
appropriately during decryption. Any padding characters that were added to
make the plaintext fit into digraphs should be removed to recover the original
message accurately.

Code:-
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define SIZE 5

void generateKeyTable(char key[], char keyTable[SIZE][SIZE]) {


int flag[26] = {0}, i, j = 0;
for (i = 0; key[i]; i++)
if (key[i] != 'j' && flag[key[i] - 'a']++ == 0)
keyTable[j / SIZE][j++ % SIZE] = key[i];
for (i = 0; i < 26; i++)
if (flag[i] == 0 && (i + 'a') != 'j')
keyTable[j / SIZE][j++ % SIZE] = i + 'a';
}

void search(char keyTable[SIZE][SIZE], char a, char b, int *row1, int


5|Page
Nakul Lohar
210303105503
7B23
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311

B.Tech – 4th Year 7th Semester


*col1, int *row2, int *col2) {
int i, j;
if (a == 'j') a = 'i';
if (b == 'j') b = 'i';
for (i = 0; i < SIZE; i++)
for (j = 0; j < SIZE; j++) {
if (keyTable[i][j] == a) *row1 = i, *col1 = j;
if (keyTable[i][j] == b) *row2 = i, *col2 = j;
}
}

void decrypt(char str[], char keyTable[SIZE][SIZE]) {


int i, row1, col1, row2, col2, len = strlen(str);
for (i = 0; i < len; i += 2) {
search(keyTable, str[i], str[i + 1], &row1, &col1, &row2, &col2);
if (row1 == row2) {
str[i] = keyTable[row1][(col1 - 1 + SIZE) % SIZE];
str[i + 1] = keyTable[row2][(col2 - 1 + SIZE) % SIZE];
} else if (col1 == col2) {
str[i] = keyTable[(row1 - 1 + SIZE) % SIZE][col1];
str[i + 1] = keyTable[(row2 - 1 + SIZE) % SIZE][col2];
} else {
str[i] = keyTable[row1][col2];
str[i + 1] = keyTable[row2][col1];
}
}
}

int main() {
char key[] = "keyword";
char str[] = "helloplayfaircipher"; // Example encrypted text
char keyTable[SIZE][SIZE];
int i;

for (i = 0; str[i]; i++) str[i] = tolower(str[i]);

generateKeyTable(key, keyTable);
printf("Key Table:\n");
6|Page
Nakul Lohar
210303105503
7B23
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311

B.Tech – 4th Year 7th Semester


for (i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++)
printf("%c ", keyTable[i][j]);
printf("\n");
}

printf("Encrypted Text: %s\n", str);


decrypt(str, keyTable);
printf("Decrypted Text: %s\n", str);

return 0;
}

Code:-

Result:- The practical of Playfair Cipher Encryption and Decryption has been
successfully completed.

7|Page
Nakul Lohar
210303105503
7B23
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311

B.Tech – 4th Year 7th Semester

Practical – 4
Aim:- A) Hill Cipher Encrpytion

Theory:-

• Polygraphic Substitution Cipher: The Hill Cipher is a polygraphic substitution


cipher, which means it encrypts blocks of plaintext letters (e.g., digraphs,
trigraphs) rather than single letters. This makes it more secure against frequency
analysis attacks compared to monoalphabetic ciphers.

• Linear Algebra Basis: The encryption process of the Hill Cipher relies on linear
algebra. It uses matrix multiplication to transform the plaintext vector into the
ciphertext vector, using a key matrix. The key matrix must be invertible in the
context of modular arithmetic (mod 26 for the English alphabet).

• Key Matrix: The key for the Hill Cipher is represented as a square matrix of size
n×nn \times nn×n. The size of this matrix determines the block size of the
plaintext it encrypts. For instance, a 2x2 key matrix will encrypt two letters at a
time, while a 3x3 key matrix will encrypt three letters at a time.

• Padding: If the length of the plaintext is not a multiple of the matrix size,
padding characters (commonly 'X') are added to the plaintext to fill up the block.
Similarly, if the key length is not a perfect square, padding characters are added
to form a complete square matrix.

Code:

import java.util.Scanner;

public class HillCipher {


// Function to multiply matrices and get modulo 26
private static int[] multiplyAndMod(int[][] keyMatrix, int[]
messageVector) {
int[] resultVector = new int[messageVector.length];
for (int i = 0; i < keyMatrix.length; i++) {
for (int j = 0; j < keyMatrix.length; j++) {
resultVector[i] += keyMatrix[i][j] * messageVector[j];
8|Page
Nakul Lohar
210303105503
7B23
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311

B.Tech – 4th Year 7th Semester


}
resultVector[i] %= 26;
}
return resultVector;
}

// Function to convert character to integer


private static int charToInt(char c) {
return (c - 'A');
}

// Function to convert integer to character


private static char intToChar(int i) {
return (char) (i + 'A');
}

// Function to construct key matrix from key string


private static int[][] constructKeyMatrix(String key, int size) {
int[][] keyMatrix = new int[size][size];
int k = 0;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
keyMatrix[i][j] = charToInt(key.charAt(k++));
}
}
return keyMatrix;
}

// Function to perform Hill Cipher encryption


public static String encrypt(String message, String key) {
message = message.toUpperCase().replaceAll("\\s", "");
key = key.toUpperCase().replaceAll("\\s", "");

int matrixSize = (int) Math.ceil(Math.sqrt(key.length()));


int requiredLength = matrixSize * matrixSize;

// Pad the key to make it a perfect square matrix


while (key.length() < requiredLength) {
9|Page
Nakul Lohar
210303105503
7B23
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311

B.Tech – 4th Year 7th Semester


key += 'X';
}

int[][] keyMatrix = constructKeyMatrix(key, matrixSize);

int messageLength = message.length();


// Pad the message to fit the matrix size
while (messageLength % matrixSize != 0) {
message += 'X';
messageLength++;
}

StringBuilder cipherText = new StringBuilder();

for (int i = 0; i < messageLength; i += matrixSize) {


int[] messageVector = new int[matrixSize];
for (int j = 0; j < matrixSize; j++) {
messageVector[j] = charToInt(message.charAt(i + j));
}

int[] resultVector = multiplyAndMod(keyMatrix, messageVector);

for (int j = 0; j < matrixSize; j++) {


cipherText.append(intToChar(resultVector[j]));
}
}

return cipherText.toString();
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

// Input the message


System.out.println("Enter the message to be encrypted:");
String message = sc.nextLine();

// Input the key


10 | P a g
Nakul Lohar e
210303105503
7B23
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311

B.Tech – 4th Year 7th Semester


System.out.println("Enter the key:");
String key = sc.nextLine();

String cipherText = encrypt(message, key);

System.out.println("Encrypted message: " + cipherText);

sc.close();
}
}

Output:

11 | P a g
Nakul Lohar e
210303105503
7B23
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311

B.Tech – 4th Year 7th Semester

Aim:- B) Hill Cipher Decryption

Theory:-

• Matrix Inversion: Decryption in the Hill Cipher involves using the inverse of the
key matrix. This inverse matrix is applied to the ciphertext blocks to retrieve the
original plaintext. Finding the matrix inverse involves linear algebra techniques
such as calculating the determinant, adjoint, and applying modular arithmetic.

• Block Decryption: Similar to encryption, decryption is done in blocks of letters


(e.g., digraphs, trigraphs) determined by the size of the key matrix. Each block of
ciphertext is multiplied by the inverse key matrix to convert it back to the
corresponding block of plaintext.

Code:-
import java.util.Scanner;
public class HillCipherDecryption {
private static int[] multiplyAndMod(int[][] keyMatrix, int[]
messageVector) {
int[] resultVector = new int[messageVector.length];
for (int i = 0; i < keyMatrix.length; i++) {
for (int j = 0; j < keyMatrix.length; j++) {
resultVector[i] += keyMatrix[i][j] * messageVector[j];
}
resultVector[i] %= 26;
}
return resultVector;
}

private static int charToInt(char c) {


return (c - 'A');
}

12 | P a g
Nakul Lohar e
210303105503
7B23
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311

B.Tech – 4th Year 7th Semester


private static char intToChar(int i) {
return (char) (i + 'A');
}

private static int[][] constructKeyMatrix(String key, int size) {


int[][] keyMatrix = new int[size][size];
int k = 0;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
keyMatrix[i][j] = charToInt(key.charAt(k++));
}
}
return keyMatrix;
}

private static int modInverse(int a, int m) {


a = a % m;
for (int x = 1; x < m; x++) {
if ((a * x) % m == 1) return x;
}
return 1;
}

private static int findDeterminant(int[][] matrix, int n) {


int determinant = 0;
if (n == 1) {
return matrix[0][0];
}
int[][] temp = new int[n][n];
int sign = 1;
for (int f = 0; f < n; f++) {
getCofactor(matrix, temp, 0, f, n);
determinant += sign * matrix[0][f] * findDeterminant(temp, n - 1);
sign = -sign;
}
return determinant;
}

13 | P a g
Nakul Lohar e
210303105503
7B23
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311

B.Tech – 4th Year 7th Semester


private static void getCofactor(int[][] matrix, int[][] temp, int p, int q, int
n) {
int i = 0, j = 0;
for (int row = 0; row < n; row++) {
for (int col = 0; col < n; col++) {
if (row != p && col != q) {
temp[i][j++] = matrix[row][col];
if (j == n - 1) {
j = 0;
i++;
}
}
}
}
}

private static void adjoint(int[][] matrix, int[][] adj, int n) {


if (n == 1) {
adj[0][0] = 1;
return;
}
int sign = 1;
int[][] temp = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
getCofactor(matrix, temp, i, j, n);
sign = ((i + j) % 2 == 0) ? 1 : -1;
adj[j][i] = (sign * findDeterminant(temp, n - 1)) % 26;
if (adj[j][i] < 0) {
adj[j][i] += 26;
}
}
}
}

private static boolean inverse(int[][] matrix, int[][] inverse, int n) {


int det = findDeterminant(matrix, n);
int invDet = modInverse(det % 26, 26);
14 | P a g
Nakul Lohar e
210303105503
7B23
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311

B.Tech – 4th Year 7th Semester


if (invDet == 0) {
return false;
}
int[][] adj = new int[n][n];
adjoint(matrix, adj, n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
inverse[i][j] = (adj[i][j] * invDet) % 26;
if (inverse[i][j] < 0) {
inverse[i][j] += 26;
}
}
}
return true;
}

public static String decrypt(String message, String key) {


message = message.toUpperCase().replaceAll("\\s", "");
key = key.toUpperCase().replaceAll("\\s", "");

int matrixSize = (int) Math.ceil(Math.sqrt(key.length()));


int requiredLength = matrixSize * matrixSize;

// Pad the key to make it a perfect square matrix


while (key.length() < requiredLength) {
key += 'X';
}

int[][] keyMatrix = constructKeyMatrix(key, matrixSize);


int[][] inverseKeyMatrix = new int[matrixSize][matrixSize];

if (!inverse(keyMatrix, inverseKeyMatrix, matrixSize)) {


throw new IllegalArgumentException("Key matrix is not invertible.");
}

int messageLength = message.length();


// Pad the message to fit the matrix size
while (messageLength % matrixSize != 0) {
15 | P a g
Nakul Lohar e
210303105503
7B23
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311

B.Tech – 4th Year 7th Semester


message += 'X';
messageLength++;
}

StringBuilder plainText = new StringBuilder();

for (int i = 0; i < messageLength; i += matrixSize) {


int[] messageVector = new int[matrixSize];
for (int j = 0; j < matrixSize; j++) {
messageVector[j] = charToInt(message.charAt(i + j));
}

int[] resultVector = multiplyAndMod(inverseKeyMatrix,


messageVector);

for (int j = 0; j < matrixSize; j++) {


plainText.append(intToChar(resultVector[j]));
}
}

return plainText.toString();
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.println("Enter the ciphertext to be decrypted:");


String cipherText = sc.nextLine();

System.out.println("Enter the key:");


String key = sc.nextLine();

try {
String plainText = decrypt(cipherText, key);
System.out.println("Decrypted message: " + plainText);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
16 | P a g
Nakul Lohar e
210303105503
7B23
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311

B.Tech – 4th Year 7th Semester

sc.close();
}
}

Output:-

Result:- The practical of Hill Cipher Encryption and Decryption has been
successfully completed.

17 | P a g
Nakul Lohar e
210303105503
7B23

You might also like