# Define the Polybius matrix
# This matrix maps numerical pairs to characters for decryption
polybius <- matrix(c(" ", "Z", "M", "D", " ", "K", "W", "Q", " ", "G",
                     "V", " ", "A", " ", "R", " ", "E", " ", "T", "O",
                     " ", "J", "I", "S", "B", "P", "Y", " ", "F", " ",
                     "L", " ", " ", "C", " ", "U", "H", "N", " ", "X"), 
                   nrow = 4, byrow = TRUE)

# Assign row and column labels for better reference
rownames(polybius) <- 0:3
colnames(polybius) <- 0:9

# Function to find numeric coordinates of characters
get_coordinates <- function(text, matrix) {
  coords <- sapply(text, function(char) {
    pos <- which(matrix == char, arr.ind = TRUE)
    if (length(pos) == 2) (pos[1] - 1) * 10 + (pos[2] - 1) else NA
  })
  coords
}

# Encryption Process
message <- "RAISETHEFLAG"
keyword <- "APPLE"

# Split message and keyword into individual characters
msg_chars <- unlist(strsplit(message, ""))
key_chars <- rep(unlist(strsplit(keyword, "")), length.out = length(msg_chars))

# Get numeric coordinates for the message and keyword
msg_coords <- get_coordinates(msg_chars, polybius)
key_coords <- get_coordinates(key_chars, polybius)

# Encrypt the message by adding corresponding coordinates
cipher_coords <- (msg_coords + key_coords)

# Format ciphertext into 5-character blocks
ciphertext <- paste(cipher_coords, collapse = "")
formatted_blocks <- sapply(seq(1, nchar(ciphertext), by = 5), function(i) {
  block <- substr(ciphertext, i, i + 4)
  if (nchar(block) < 5) 
    paste0(block, paste(sample(0:9, 5 - nchar(block), replace = TRUE), collapse = ""))
  else block
})

# Display the encrypted blocks
formatted_blocks

# Decryption Process
ciphertext <- "48521 82559 53320 83151 44382 13349 40352 42260 48521 84349 48343 23518"
keyword <- "LEMON"

# Remove spaces and split ciphertext into numeric pairs
cipher_pairs <- as.numeric(strsplit(gsub(" ", "", ciphertext), "(?<=\\G..)", perl = TRUE)[[1]])

# Get numeric coordinates for the keyword
key_coords <- get_coordinates(rep(unlist(strsplit(keyword, "")), length.out = length(cipher_pairs)), polybius)

# Decrypt the ciphertext by subtracting the keyword coordinates
plaintext_coords <- (cipher_pairs - key_coords + 40) %% 40

# Map numeric coordinates back to characters
deciphered_text <- sapply(plaintext_coords, function(coord) {
  row <- coord %/% 10
  col <- coord %% 10
  char <- polybius[row + 1, col + 1]
  if (char == " ") NULL else char
})

# Combine characters to form the plaintext message
plaintext <- paste(deciphered_text, collapse = "")
plaintext