0% found this document useful (0 votes)
8 views8 pages

Caesar Cipher

The document contains implementations of three encryption algorithms: Caesar cipher, Playfair cipher, and Hill cipher in Java. Each algorithm includes methods for encryption and decryption, along with user interaction through a console menu for inputting plaintext, ciphertext, and keys. The code demonstrates how to handle character shifting, key matrix generation, and matrix operations for encryption and decryption processes.

Uploaded by

atharvabhangale3
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)
8 views8 pages

Caesar Cipher

The document contains implementations of three encryption algorithms: Caesar cipher, Playfair cipher, and Hill cipher in Java. Each algorithm includes methods for encryption and decryption, along with user interaction through a console menu for inputting plaintext, ciphertext, and keys. The code demonstrates how to handle character shifting, key matrix generation, and matrix operations for encryption and decryption processes.

Uploaded by

atharvabhangale3
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/ 8

//Caesar cipher

import java.util.*;

public class Main {


public static String encrypt(String plaintext, int shift) {
StringBuilder ciphertext = new StringBuilder();
for (char character : plaintext.toCharArray()) {
if (Character.isLetter(character)) {
char shiftedCharacter = shiftLetter(character, shift);
ciphertext.append(shiftedCharacter);
} else {
ciphertext.append(character);
}
}
return ciphertext.toString();
}

private static char shiftLetter(char letter, int shift) {


if (Character.isUpperCase(letter)) {
return (char) (((letter - 'A' + shift) % 26 + 26) % 26 + 'A');
} else if (Character.isLowerCase(letter)) {
return (char) (((letter - 'a' + shift) % 26 + 26) % 26 + 'a');
} else {
return letter;
}
}

public static String decrypt(String ciphertext, int shift) {


return encrypt(ciphertext, -shift);
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
int choice;

do {
System.out.println("\nMenu:");
System.out.println("1. Encrypt");
System.out.println("2. Decrypt");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");

choice = sc.nextInt();
sc.nextLine(); // Consume newline

switch (choice) {
case 1:
System.out.print("Enter plaintext: ");
String plaintext = sc.nextLine();
System.out.print("Enter shift value: ");
int encryptShift = sc.nextInt();
sc.nextLine();
String encrypted = encrypt(plaintext, encryptShift);
System.out.println("Encrypted: " + encrypted);
break;

case 2:
System.out.print("Enter ciphertext: ");
String ciphertext = sc.nextLine();
System.out.print("Enter shift value: ");
int decryptShift = sc.nextInt();
sc.nextLine();
String decrypted = decrypt(ciphertext, decryptShift);
System.out.println("Decrypted: " + decrypted);
break;

case 3:
System.out.println("Exiting the program.");
break;

default:
System.out.println("Invalid choice. Please try
again.");
}
} while (choice != 3);

sc.close();
}
}

//Playfair cipher
import java.util.*;

public class Main {

private static char[][] keyMatrix = new char[5][5];


private static final String ALPHABET = "ABCDEFGHIKLMNOPQRSTUVWXYZ";

public static void generateKeyMatrix(String key) {


StringBuilder processedKey = new StringBuilder();
Set<Character> used = new HashSet<>();
for (char c : key.toUpperCase().toCharArray()) {
if (c == 'J') c = 'I';
if (!used.contains(c) && ALPHABET.indexOf(c) != -1) {
processedKey.append(c);
used.add(c);
}
}
for (char c : ALPHABET.toCharArray()) {
if (!used.contains(c)) {
processedKey.append(c);
used.add(c);
}
}
int index = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
keyMatrix[i][j] = processedKey.charAt(index++);
}
}
}

public static String encrypt(String plaintext, String key) {


generateKeyMatrix(key);
plaintext = preprocessPlaintext(plaintext);
StringBuilder ciphertext = new StringBuilder();
for (int i = 0; i < plaintext.length(); i += 2) {
char a = plaintext.charAt(i);
char b = plaintext.charAt(i + 1);
int[] posA = findPosition(a);
int[] posB = findPosition(b);
if (posA[0] == posB[0]) {
ciphertext.append(keyMatrix[posA[0]][(posA[1] + 1) % 5]);
ciphertext.append(keyMatrix[posB[0]][(posB[1] + 1) % 5]);
} else if (posA[1] == posB[1]) {
ciphertext.append(keyMatrix[(posA[0] + 1) % 5][posA[1]]);
ciphertext.append(keyMatrix[(posB[0] + 1) % 5][posB[1]]);
} else {
ciphertext.append(keyMatrix[posA[0]][posB[1]]);
ciphertext.append(keyMatrix[posB[0]][posA[1]]);
}
}
return ciphertext.toString();
}

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


generateKeyMatrix(key);
StringBuilder plaintext = new StringBuilder();
for (int i = 0; i < ciphertext.length(); i += 2) {
char a = ciphertext.charAt(i);
char b = ciphertext.charAt(i + 1);
int[] posA = findPosition(a);
int[] posB = findPosition(b);
if (posA[0] == posB[0]) {
plaintext.append(keyMatrix[posA[0]][(posA[1] + 4) % 5]);
plaintext.append(keyMatrix[posB[0]][(posB[1] + 4) % 5]);
} else if (posA[1] == posB[1]) {
plaintext.append(keyMatrix[(posA[0] + 4) % 5][posA[1]]);
plaintext.append(keyMatrix[(posB[0] + 4) % 5][posB[1]]);
} else {
plaintext.append(keyMatrix[posA[0]][posB[1]]);
plaintext.append(keyMatrix[posB[0]][posA[1]]);
}
}
return plaintext.toString();
}

private static String preprocessPlaintext(String plaintext) {


StringBuilder processed = new StringBuilder();
plaintext = plaintext.toUpperCase().replace("J", "I");
for (int i = 0; i < plaintext.length(); i++) {
char c = plaintext.charAt(i);
if (ALPHABET.indexOf(c) != -1) {
if (processed.length() > 0 &&
processed.charAt(processed.length() - 1) == c) {
processed.append('X');
}
processed.append(c);
}
}
if (processed.length() % 2 != 0) {
processed.append('X');
}
return processed.toString();
}

private static int[] findPosition(char c) {


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

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
int choice;

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


String key = scanner.nextLine();

do {
System.out.println("\nMenu:");
System.out.println("1. Encrypt");
System.out.println("2. Decrypt");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
scanner.nextLine(); // Consume newline

switch (choice) {
case 1:
System.out.print("Enter the plaintext: ");
String plaintext = scanner.nextLine();
String encrypted = encrypt(plaintext, key);
System.out.println("Encrypted: " + encrypted);
break;
case 2:
System.out.print("Enter the ciphertext: ");
String ciphertext = scanner.nextLine();
String decrypted = decrypt(ciphertext, key);
System.out.println("Decrypted: " + decrypted);
break;
case 3:
System.out.println("Exiting the program.");
break;
default:
System.out.println("Invalid choice. Please try
again.");
}
} while (choice != 3);

scanner.close();
}
}

//Hillcipher
import java.util.*;

public class Main {


public static String encrypt(int[][] keyMatrix, String plainText, int
n) {
StringBuilder cipherText = new StringBuilder();
plainText = plainText.toUpperCase().replaceAll("[^A-Z]", "");
int len = plainText.length();

while (len % n != 0) {
plainText += 'X';
len++;
}

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


int[] block = new int[n];
for (int j = 0; j < n; j++) {
block[j] = plainText.charAt(i + j) - 'A';
}

int[] result = new int[n];


for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
result[j] += keyMatrix[j][k] * block[k];
}
result[j] %= 26;
}

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


cipherText.append((char) (result[j] + 'A'));
}
}
return cipherText.toString();
}

public static String decrypt(int[][] keyMatrix, String cipherText, int


n) {
StringBuilder plainText = new StringBuilder();
cipherText = cipherText.toUpperCase().replaceAll("[^A-Z]", "");

int[][] inverseMatrix = findInverseMatrix(keyMatrix, n);


if (inverseMatrix == null) {
return "Decryption not possible (Key matrix is not
invertible).";
}

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


int[] block = new int[n];
for (int j = 0; j < n; j++) {
block[j] = cipherText.charAt(i + j) - 'A';
}

int[] result = new int[n];


for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
result[j] += inverseMatrix[j][k] * block[k];
}
result[j] %= 26;
if (result[j] < 0) result[j] += 26;
}

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


plainText.append((char) (result[j] + 'A'));
}
}
return plainText.toString();
}

public static int[][] findInverseMatrix(int[][] matrix, int n) {


int det = determinant(matrix, n) % 26;
if (det < 0) det += 26;
int detInverse = modularInverse(det, 26);
if (detInverse == -1) return null;

int[][] adjMatrix = adjoint(matrix, n);


int[][] inverseMatrix = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
inverseMatrix[i][j] = (adjMatrix[i][j] * detInverse) % 26;
if (inverseMatrix[i][j] < 0) inverseMatrix[i][j] += 26;
}
}
return inverseMatrix;
}

public static int determinant(int[][] matrix, int n) {


if (n == 1) return matrix[0][0];
if (n == 2) return matrix[0][0] * matrix[1][1] - matrix[0][1] *
matrix[1][0];

int det = 0;
for (int i = 0; i < n; i++) {
det += (i % 2 == 0 ? 1 : -1) * matrix[0][i] *
determinant(minor(matrix, 0, i, n), n - 1);
}
return det;
}

public static int[][] minor(int[][] matrix, int row, int col, int n) {
int[][] minor = new int[n - 1][n - 1];
for (int i = 0, mi = 0; i < n; i++) {
if (i == row) continue;
for (int j = 0, mj = 0; j < n; j++) {
if (j == col) continue;
minor[mi][mj++] = matrix[i][j];
}
mi++;
}
return minor;
}

public static int[][] adjoint(int[][] matrix, int n) {


int[][] adj = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
adj[j][i] = ((i + j) % 2 == 0 ? 1 : -1) *
determinant(minor(matrix, i, j, n), n - 1);
}
}
return adj;
}

public static int modularInverse(int a, int m) {


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

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
int choice;

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


int n = scanner.nextInt();

int[][] keyMatrix = new int[n][n];


System.out.println("Enter the key matrix (" + n + "x" + n + ", row
by row): ");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
keyMatrix[i][j] = scanner.nextInt();
}
}

scanner.nextLine();

do {
System.out.println("\nMenu:");
System.out.println("1. Encrypt");
System.out.println("2. Decrypt");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
scanner.nextLine();

switch (choice) {
case 1:
System.out.print("Enter the plaintext: ");
String plainText = scanner.nextLine();
System.out.println("Encrypted: " + encrypt(keyMatrix,
plainText, n));
break;
case 2:
System.out.print("Enter the ciphertext: ");
String cipherText = scanner.nextLine();
System.out.println("Decrypted: " + decrypt(keyMatrix,
cipherText, n));
break;
case 3:
System.out.println("Exiting the program.");
break;
default:
System.out.println("Invalid choice. Please try
again.");
}
} while (choice != 3);

scanner.close();
}
}
Enter the size of the key matrix:
3

Enter the key matrix (3x3, row by row):

6 24 1

13 16 10

20 17 15

Menu:

1. Encrypt

2. Decrypt

3. Exit

Enter your choice: 1

Enter the plaintext: Atharva

Encrypted: VKMNOGDAI

You might also like