#Mohammed Talha Sajidhusein Vasanwala-2316054
# Define the vigenere Matrix
vigenere <- matrix(nrow = 26, ncol = 26)
# Define the Variable letter and Stored the Letters
letters <- 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")

# Stored the data into the vigenere matrix using 2dimensional for loop
for (i in 1:26) {
  for (j in 1:26) {
    vigenere[i, j] <- letters[(i + j - 2) %% 26 + 1]
  }
}

# Add the label to vigenere matrix row and column 
colnames(vigenere) <- letters
rownames(vigenere) <- letters

# Print vigenere matrix
print("Vigenere Matrix:")
print(vigenere)



# Define the keyphrase/ UWTSDSWANSEA
keyphrase <- "UWTSDSWANSEA"

# Input the plaintext message
plaintext <- "CAPTURETHEFLAG"

# Initialize an empty string for the ciphertext
ciphertext <- ""

# Perform Vigenère encryption
for (i in 1:nchar(plaintext)) {
  # Get the current character from the plaintext
  char <- substr(plaintext, i, i)
  
  # Find the corresponding key character based on the keyphrase
  key_char <- substr(keyphrase, (i - 1) %% nchar(keyphrase) + 1, (i - 1) %% nchar(keyphrase) + 1)
  
  # Find the row for the key character in the Vigenère table
  row <- which(letters == char)
  
  # Find the column for the key character in the Vigenère table
  col <- which(colnames(vigenere) == key_char)
  
  # Encrypt the character and append it to the ciphertext
 ciphertext <- paste(ciphertext, letters[(row + col - 2) %% 26 + 1], sep = "")
  
}

# Output the ciphertext
print(ciphertext)



# 3. Decryption using the keyphrase RPROGRAMMING and provided ciphertext
keyphrase <- "RPROGRAMMING"
ciphertext <- "ETMSXWISTBNHRIKZKKHMFGBAUDECZEEQPBBCZ"


# Initialize an empty string for the decrypted plaintext
plaintext <- ""

# Decrypting the ciphertext using the keyphrase
for (i in 1:nchar(ciphertext)) {
  # Get the current character from the ciphertext
  letter <- substr(ciphertext, i, i)
  
  # Determine the index of the key character based on the keyphrase length
  keyIndex <- (i - 1) %% nchar(keyphrase) + 1
  
  # Find the column index in the Vigenère table based on the keyphrase character
  col <- which(colnames(vigenere) == substr(keyphrase, keyIndex, keyIndex))
  
  # Find the row index in the Vigenère table corresponding to the ciphertext character
  row <- which(vigenere[, col] == letter)
  
  # Append the decrypted character to the plaintext
  plaintext <- paste(plaintext, letters[row], sep = "")
}

# Displaying the decrypted plaintext
print("Decrypted Plaintext:")
print(plaintext)
