playfair

mail@pastecode.io avatar
unknown
java
2 years ago
4.8 kB
1
Indexable
Never
import java.util.Scanner;

public class PlayFair {
    private static char[][] keyMatrix;

    // Initialize key matrix
    static {
        keyMatrix = new char[][]{
                {'M', 'O', 'N', 'A', 'R'},
                {'C', 'H', 'Y', 'B', 'D'},
                {'E', 'F', 'G', 'I', 'K'},
                {'L', 'P', 'Q', 'S', 'T'},
                {'U', 'V', 'W', 'X', 'Z'}
        };
    }

    // Encrypts the given message using the PlayFair algorithm and the key matrix
    public static String encrypt(String message) {
        // Remove spaces and non-alphabetic characters from the message
        message = message.replaceAll("[^A-Za-z]", "");
        message = message.toUpperCase();

        // Insert X between double letters
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < message.length(); i++) {
            char c = message.charAt(i);
            sb.append(c);
            if (i < message.length() - 1 && c == message.charAt(i + 1)) {
                sb.append('X');
            }
        }
        message = sb.toString();

        // If the message has an odd length, append an X at the end
        if (message.length() % 2 == 1) {
            message += 'X';
        }

        // Initialize the encrypted message
        String encryptedMessage = "";

        // Encrypt the message in pairs of letters
        for (int i = 0; i < message.length(); i += 2) {
            char c1 = message.charAt(i);
            char c2 = message.charAt(i + 1);

            // Get the indices of the characters in the key matrix
            int[] index1 = getCharIndex(c1);
            int[] index2 = getCharIndex(c2);

            // Encrypt the pair of characters using the key matrix
            if (index1[0] == index2[0]) {
                // Same row - replace with characters to the right (wrapping around if necessary)
                encryptedMessage += keyMatrix[index1[0]][(index1[1] + 1) % 5];
                encryptedMessage += keyMatrix[index2[0]][(index2[1] + 1) % 5];
            } else if (index1[1] == index2[1]) {
                // Same column - replace with characters below (wrapping around if necessary)
                encryptedMessage += keyMatrix[(index1[0] + 1) % 5][index1[1]];
                encryptedMessage += keyMatrix[(index2[0] + 1) % 5][index2[1]];
            } else {
                // Different row and column - replace with characters in the same row, but in the columns of the other character
                encryptedMessage += keyMatrix[index1[0]][index2[1]];
                encryptedMessage += keyMatrix[index2[0]][index1[1]];
            }
        }

        return encryptedMessage;
    }

    // Decrypts the given encrypted message using the PlayFair algorithm and the key matrix
    public static String decrypt(String encryptedMessage) {
        // Initialize the decrypted message
        String decryptedMessage = "";

        // Decrypt the message in pairs of letters
        for (int i = 0; i < encryptedMessage.length(); i += 2) {
            char c1 = encryptedMessage.charAt(i);
            char c2 = encryptedMessage.charAt(i + 1);

            // Get the indices of the characters in the key matrix
            int[] index1 = getCharIndex(c1);
            int[] index2 = getCharIndex(c2);

            // Decrypt the pair of characters using the key matrix
            if (index1[0] == index2[0]) {
                // Same row - replace with characters to the left (wrapping around if necessary)
                decryptedMessage += keyMatrix[index1[0]][(index1[1] + 4) % 5];
                decryptedMessage += keyMatrix[index2[0]][(index2[1] + 4) % 5];
            } else if (index1[1] == index2[1]) {
                // Same column - replace with characters above (wrapping around if necessary)
                decryptedMessage += keyMatrix[(index1[0] + 4) % 5][index1[1]];
                decryptedMessage += keyMatrix[(index2[0] + 4) % 5][index2[1]];
            } else {
                // Different row and column - replace with characters in the same row, but in the columns of the other character
                decryptedMessage += keyMatrix[index1[0]][index2[1]];
                decryptedMessage += keyMatrix[index2[0]][index1[1]];
            }
        }

        // Remove X characters that were inserted between double letters
        decryptedMessage = decryptedMessage.replace("X", "");

        return decryptedMessage;
    }

    // Returns the indices (row and column) of the given character in the key matrix
    private static int[] getCharIndex(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;
    }
}