Practical 2
Practical 2
:230843116012
PRACTICAL – 2
AIM:-Implement playfair cipher. The plaintext is paired in two characters.
Discuss the advantage of polyalphabetic cipher over monoalphabetic
cipher.
Key = MONARCHY
Plaintext = ar mu hs ea
Ciphertext = RM CM BP IM
CODE:-
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define SIZE 5
#define MAX_INPUT 100
4
Enrollment No.:230843116012
if (first == second) {
second = 'X';
i--;
}
if (row1 == row2) {
ciphertext[cipherIndex++] = matrix[row1][(col1 + 1) % SIZE];
ciphertext[cipherIndex++] = matrix[row2][(col2 + 1) % SIZE];
} else if (col1 == col2) {
ciphertext[cipherIndex++] = matrix[(row1 + 1) % SIZE][col1];
ciphertext[cipherIndex++] = matrix[(row2 + 1) % SIZE][col2];
} else {
ciphertext[cipherIndex++] = matrix[row1][col2];
ciphertext[cipherIndex++] = matrix[row2][col1];
}
}
ciphertext[cipherIndex] = '\0';
}
5
Enrollment No.:230843116012
if (row1 == row2) {
plaintext[plainIndex++] = matrix[row1][(col1 + SIZE - 1) % SIZE];
plaintext[plainIndex++] = matrix[row2][(col2 + SIZE - 1) % SIZE];
} else if (col1 == col2) {
plaintext[plainIndex++] = matrix[(row1 + SIZE - 1) % SIZE][col1];
plaintext[plainIndex++] = matrix[(row2 + SIZE - 1) % SIZE][col2];
} else {
plaintext[plainIndex++] = matrix[row1][col2];
plaintext[plainIndex++] = matrix[row2][col1];
}
}
plaintext[plainIndex] = '\0';
}
void clearInputBuffer() {
int c;
while ((c = getchar()) != '\n' && c != EOF);
}
int main() {
char key[MAX_INPUT];
char plaintext[MAX_INPUT];
char matrix[SIZE][SIZE];
char processedText[MAX_INPUT] = {0};
char result[MAX_INPUT] = {0};
char formattedOutput[MAX_INPUT * 2] = {0};
char choice;
createPlayfairMatrix(key, matrix);
printMatrix(matrix);
prepareText(plaintext, processedText);
7
Enrollment No.:230843116012
if (toupper(choice) == 'E') {
playfairEncode(matrix, processedText, result);
printf("Plaintext: %s\n", plaintext);
formatInPairs(result, formattedOutput);
printf("Ciphertext: %s\n", formattedOutput);
} else if (toupper(choice) == 'D') {
playfairDecode(matrix, processedText, result);
printf("Ciphertext: %s\n", plaintext);
formatInPairs(result, formattedOutput);
printf("Plaintext: %s\n", formattedOutput);
} else {
printf("Invalid choice. Exiting.\n");
return 1;
}
return 0;
}
OUTPUT