# Author: Lirui Bi
# Title: One encryption method based upon a Polybius cipher
# Time: 24.11.2021
#--------------------------------------------------------------------
# Create Polybius matrix
Polybius<-matrix(c(NA, "Z", "M", "D", NA, "K", "W", "Q", NA, "G",
                   "V", NA, "A", NA, "R", NA, "E", NA, "T", "O",
                   NA, "J", "I", "S", "B", "P", "Y", NA, "F", NA,
                   "L", NA, NA, "C", NA, "U", "H", "N", NA, "X"),
                 ncol = 10, byrow = T)

# Add row names using rownames()
rownames(Polybius)<-c(0, 1, 2, 3)

# Add column names using colnames()
colnames(Polybius)<-c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

# Display Polybius
Polybius

# Question2
# Create Message vector
Message<-("CAPTURETHEHILL")

# Display Message
Message

# Create ciphertext vector
ciphertext<-NULL

# Create ciphertext1 vector
ciphertext1<-NULL

for (z in 1:nchar(Message)) 
{
  # Extract every letter of Message
  letter<-substring(Message, z, z) 
  
  # Loop to find the position[i,j] of each letter in Polybius
  for (i in 1:nrow(Polybius)) 
  {
    for (j in 1:ncol(Polybius)) 
    {
      # If the element is not NA
      if(!is.na(Polybius[i,j])) 
      {
        if(Polybius[i,j] == letter)
        {
          # Sorry, I am not sure which format it should be displayed in, 
          # so I wrote two  lines codes
          # Update ciphertext vector and encrypt the letter
          ciphertext<-c(ciphertext, as.numeric(paste(i-1, j-1,
                                            sep="", collapse="")))
          # Or
          ciphertext1<-c(ciphertext1, c(i-1, j-1))
        }
      }
    }
  }
}

# Display ciphertext
ciphertext 

# Display ciphertext1
ciphertext1

# Question3
# Convert ciphertext vector to a long character prefinaltext vector
prefinaltext<-paste(ciphertext, collapse="")

# Display prefinaltext
prefinaltext

# Create finaltext vector
finaltext<-NULL

# Calculate the number of groups of finaltext 
n<-ceiling(nchar(prefinaltext)/5)

for (a in 1:n) 
{
  # Extract characters from prefinaltext in groups of 5
  temp<-substring(prefinaltext, a*5-4, a*5)
  if(nchar(temp)<5) # If the number of chr in temp is less than 5
  {
    b<-5-nchar(temp) # Number of characters to be added to temp
    c<-floor(runif(b, 0, 10)) # Randomly generate b integers from 0-9
    c<-paste(c, collapse="")
    temp<-paste(temp, c, sep = "" ) # Update finaltext vector
    #print(temp)
    finaltext<-paste(finaltext, temp) # Update finaltext vector
  }
  else
  finaltext<-paste(finaltext, temp) # Update finaltext vector
  
}

# Display finaltext
finaltext

