require "table2" enum chao begin encrypt, decrypt end local function exec(text, mode, show_steps) local len = #text local left = "HXUCZVAMDSLKPEFJRIGTWOBNYQ" local right = "PTLNBQDEOYSFAVZKGJRIHWXUMC" local etext = table.rep(len, 0) local temp = table.rep(26, "") for i = 1, len do if show_steps then print($"{left} {right}") end local index if mode == chao.encrypt then index = right:find(text[i], 1, true) etext[i] = left[index] else index = left:find(text[i], 1, true) etext[i] = right[index] end if i == len then break end -- Permute left. for j = index, 26 do temp[j - index + 1] = left[j] end for j = 1, index - 1 do temp[27 - index + j] = left[j] end local store = temp[2] for j = 3, 14 do temp[j - 1] = temp[j] end temp[14] = store left = temp:concat("") -- Permute right. for j = index, 26 do temp[j - index + 1] = right[j] end for j = 1, index - 1 do temp[27 - index + j] = right[j] end store = temp[1] for j = 2, 26 do temp[j - 1] = temp[j] end temp[26] = store store = temp[3] for j = 4, 14 do temp[j - 1] = temp[j] end temp[14] = store right = temp:concat("") end return etext:concat("") end local plain_text = "WELLDONEISBETTERTHANWELLSAID" print($"The original plaintext is : {plain_text}") io.write("\nThe left and right alphabets after each permutation ") print("during encryption are :\n") local cipher_text = exec(plain_text, chao.encrypt, true) print($"\nThe ciphertext is : {cipher_text}") local plain_text2 = exec(cipher_text, chao.decrypt, false) print($"\nThe recovered plaintext is : {plain_text2}")