# Author: Lirui Bi
# Title: One  decryption method based upon a Polybius cipher
# Time: 03.12.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

# Create Ciphertext vector
Ciphertext<-("24160 63616 14162 61935 14163 71602 26222 33719 18008")

# Display Ciphertext
Ciphertext

# Create pre_letter_code vector
pre_letter_code<-NULL

#Calculate the number of groups of Ciphertext
n1<-ceiling(nchar(Ciphertext)/6)

for (a in 1:n1) 
{
  #Extract characters from Ciphertext in groups of 6(except for space)
  temp<-substring(Ciphertext, a*6-5, a*6-1)
  # update pre_letter_code vector
  pre_letter_code<-paste(pre_letter_code, temp, sep="", collapse="")
}

# Display pre_letter_code
pre_letter_code

# Create Message vector
Message<-NULL

#Calculate the number of characters of Message vector
n2<-floor(nchar(pre_letter_code)/2)

for (a in 1:n2) 
{ 
  #Extract characters from pre_letter_code in groups of 2 
  #And convert character to numeric 
  i<-as.numeric(substring(pre_letter_code, 2*a-1, 2*a-1))
  j<-as.numeric(substring(pre_letter_code, 2*a, 2*a))
  #Because there may be randomly added numbers in the last five numbers
  #it is necessary to determine whether Polybius[i+1, j+1] is NA
  if (!is.na(Polybius[i+1, j+1])) #Or nchar(Polybius[i+1, j+1]) == 1)? 
  {
    temp<-Polybius[i+1,j+1]
    # update Message vector
    Message<-paste(Message, temp, sep="", collapse="") 
  } 
  else
    break #if Polybius[i+1, j+1] is NA, break the loop
}

# Display Message
Message

