# Define the alphabet
alphabet <- c("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z")

# Create a Vigenere matrix
vigenere_matrix <- matrix(alphabet, nrow = 26, ncol = 26, byrow = TRUE)

# Print the Vigenere matrix
print(vigenere_matrix)
# Function to encrypt a message using Vigenère cipher
vigenere_encrypt <- function(plaintext, keyphrase) {
  plaintext <- toupper(plaintext)
  keyphrase <- toupper(keyphrase)
  key_length <- nchar(keyphrase)
  
  # Repeat the keyphrase to match the length of the plaintext
  key <- paste0(rep(strsplit(keyphrase, NULL)[[1]], ceiling(nchar(plaintext)/key_length)), collapse = "")
  
  # Encrypt each character in the plaintext
  ciphertext <- ""
  for (i in 1:nchar(plaintext)) {
    if (substr(plaintext, i, i) %in% LETTERS) {
      # Encrypt only letters, leave non-letter characters unchanged
      shift <- (which(LETTERS == substr(plaintext, i, i)) - 1 +
                  which(LETTERS == substr(key, i, i)) - 1) %% 26 + 1
      ciphertext <- paste0(ciphertext, LETTERS[shift])
    } else {
      ciphertext <- paste0(ciphertext, substr(plaintext, i, i))
    }
  }
  
  return(ciphertext)
}

# Set keyphrase and plaintext
keyphrase <- "UWTSDSWANSEA"
plaintext <- "CAPTURETHEFLAG"

# Encrypt the plaintext using the keyphrase
ciphertext <- vigenere_encrypt(plaintext, keyphrase)

# Display the results
cat("Vector keyphrase:", strsplit(keyphrase, NULL)[[1]], "\n")
cat("Vector plaintext:", strsplit(plaintext, NULL)[[1]], "\n")
cat("Vector ciphertext:", strsplit(ciphertext, NULL)[[1]], "\n")
decrypt_vigenere <- function(ciphertext, keyphrase) {
  key_indices <- sapply(strsplit(keyphrase, NULL), function(char) {
    match(char, LETTERS) - 1
  })
  
  key_length <- length(key_indices)
  
  decrypted_indices <- (match(strsplit(ciphertext, NULL)[[1]], LETTERS) - key_indices) %% 26
  
  decrypted_text <- paste0(LETTERS[decrypted_indices + 1], collapse = "")
  
  return(decrypted_text)
}

# Ciphertext and keyphrase
ciphertext <- "ETMSXWISTBNHRIKZKKHMFGBAUDECZEEQPBBCZC"
keyphrase <- "RPROGRAMMING"

# Decrypt the ciphertext
plaintext <- decrypt_vigenere(ciphertext, keyphrase)

# Print the result
print(plaintext)

