0% found this document useful (0 votes)
4 views3 pages

Playfair Cipher Implementation Guide

Uploaded by

vu4f2122028
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)
4 views3 pages

Playfair Cipher Implementation Guide

Uploaded by

vu4f2122028
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

Name:Ritesh maurya ID NO:VU4F2223112

Aim: Implementation of playfair Caesar Cipher.

Program:

import [Link];

public class PlayfairCipher {


private String key;
private char[][] matrix = new char[5][5];

public PlayfairCipher(String key) {


[Link] = [Link]();
generateKeyMatrix();
}

private void generateKeyMatrix() {


boolean[] used = new boolean[26];
int k = 0, index = 0;

for (char ch : [Link]()) {


if (ch == 'J') ch = 'I'; // Treat I and J as the same letter
if (!used[ch - 'A']) {
used[ch - 'A'] = true;
matrix[k / 5][k % 5] = ch;
k++;
}
}

for (char ch = 'A'; ch <= 'Z'; ch++) {


if (ch == 'J') continue;
if (!used[ch - 'A']) {
matrix[k / 5][k % 5] = ch;
k++;
}
}
}

private String processText(String text) {


text = [Link]().replaceAll("[^A-Z]", "").replace("J", "I");

StringBuilder sb = new StringBuilder(text);


for (int i = 0; i < [Link]() - 1; i += 2) {
if ([Link](i) == [Link](i + 1)) {
[Link](i + 1, 'X');
}
}
if ([Link]() % 2 != 0) {
[Link]('X');
}
return [Link]();
}

private String encryptPair(char a, char b) {


int[] posA = findPosition(a);
int[] posB = findPosition(b);

if (posA[0] == posB[0]) {
return "" + matrix[posA[0]][(posA[1] + 1) % 5] + matrix[posB[0]][(posB[1] + 1) % 5];
} else if (posA[1] == posB[1]) {
return "" + matrix[(posA[0] + 1) % 5][posA[1]] + matrix[(posB[0] + 1) % 5][posB[1]];
} else {
return "" + matrix[posA[0]][posB[1]] + matrix[posB[0]][posA[1]];
}
}

private int[] findPosition(char ch) {


for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (matrix[i][j] == ch) {
return new int[]{i, j};
}
}
}
return null;
}

public String encrypt(String plaintext) {


plaintext = processText(plaintext);
StringBuilder ciphertext = new StringBuilder();

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


[Link](encryptPair([Link](i), [Link](i + 1)));
}
return [Link]();
}

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

[Link]("Enter the key: ");


String key = [Link]();

[Link]("Enter the plaintext: ");


String plaintext = [Link]();

PlayfairCipher cipher = new PlayfairCipher(key);


String encryptedText = [Link](plaintext);

[Link]("Encrypted Text: " + encryptedText);


}
}

Output:

Conclusion: Hence, we have successfully implemented Caesar Cipher

You might also like