Polybius Square Encryption in Python

PythonPythonBeginner
Practice Now

Introduction

In this project, you will learn how to implement the Polybius square encryption algorithm. The Polybius square is a 5x5 grid that maps each letter of the English alphabet to a pair of coordinates. By encrypting text using this method, you can create a coded message that can only be decrypted by someone with knowledge of the Polybius square.

👀 Preview

## Example 1
text = "tynam"; encryption_text = "4454331132"
## Example 2
text = "tynam123"; encryption_text = "4454331132123"
## Example 3
text = "TYnam"; encryption_text = "4454331132"
## Example 4
text = None; encryption_text = None

🎯 Tasks

In this project, you will learn:

  • How to define the Polybius square
  • How to remove spaces and convert text to lowercase
  • How to handle empty or None input
  • How to encrypt text using the Polybius square
  • How to return the encrypted text

🏆 Achievements

After completing this project, you will be able to:

  • Understand the concept of the Polybius square encryption algorithm
  • Implement the Polybius encryption algorithm in Python
  • Encrypt and decrypt text using the Polybius square
  • Handle various input scenarios, including empty or None input

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/strings("`Strings`") python/BasicConceptsGroup -.-> python/type_conversion("`Type Conversion`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-302701{{"`Polybius Square Encryption in Python`"}} python/variables_data_types -.-> lab-302701{{"`Polybius Square Encryption in Python`"}} python/strings -.-> lab-302701{{"`Polybius Square Encryption in Python`"}} python/type_conversion -.-> lab-302701{{"`Polybius Square Encryption in Python`"}} python/conditional_statements -.-> lab-302701{{"`Polybius Square Encryption in Python`"}} python/for_loops -.-> lab-302701{{"`Polybius Square Encryption in Python`"}} python/lists -.-> lab-302701{{"`Polybius Square Encryption in Python`"}} python/tuples -.-> lab-302701{{"`Polybius Square Encryption in Python`"}} python/function_definition -.-> lab-302701{{"`Polybius Square Encryption in Python`"}} python/build_in_functions -.-> lab-302701{{"`Polybius Square Encryption in Python`"}} end

Remove Spaces and Convert to Lowercase

In this step, you will learn how to prepare the input text for encryption by removing spaces and converting all characters to lowercase.

  1. Open the polybius.py file in your code editor.
  2. Add the following code to the polybius_encryption() function:
## Remove spaces and convert to lowercase
text = text.replace(" ", "").lower()

This will remove any spaces in the input text and convert all characters to lowercase.

Handle Empty or None Input

In this step, you will learn how to handle the case where the input text is empty or None.

  1. Add the following code at the beginning of the polybius_encryption() function:
if text is None:
    return None

if text == "":
    return None

This will ensure that the function returns None if the input text is None or an empty string.

  1. After completing this step the code is shown below:
def polybius_encryption(text: str) -> str:
    if text is None:
        return None

    ## Remove spaces and convert to lowercase
    text = text.replace(" ", "").lower()

    if text == "":
        return None

Set Up the Polybius Square

In this step, you will learn how to define the Polybius square, which is a 5x5 grid containing the 26 letters of the English alphabet.

  1. After the previous steps, Define the Polybius square as a list of lists, where each inner list represents a row of the square:
polybius_square = [
    ["a", "b", "c", "d", "e"],
    ["f", "g", "h", "ij", "k"],
    ["l", "m", "n", "o", "p"],
    ["q", "r", "s", "t", "u"],
    ["v", "w", "x", "y", "z"],
]

This Polybius square will be used to map the letters in the input text to their corresponding coordinates.

Encrypt the Text

In this step, you will learn how to encrypt the input text using the Polybius square.

  1. After the previous steps, add the following code to the polybius_encryption() function:
encrypted_text = ""

for char in text:
    if char.isalpha():
        for i, row in enumerate(polybius_square):
            for j, ch in enumerate(row):
                if char in ch:
                    encrypted_text += str(i + 1) + str(j + 1)
    else:
        encrypted_text += char

This code iterates over each character in the input text. If the character is a letter, it finds the corresponding coordinates in the Polybius square and appends them to the encrypted_text string. If the character is not a letter, it is added to the encrypted_text string as is.

Return the Encrypted Text

In this final step, you will learn how to return the encrypted text from the polybius_encryption() function.

  1. Add the following line at the end of the polybius_encryption() function:
return encrypted_text

This will return the encrypted text as the output of the function.

Now, the complete polybius_encryption() function should look like this:

def polybius_encryption(text: str) -> str:
    if text is None:
        return None

    ## Remove spaces and convert to lowercase
    text = text.replace(" ", "").lower()

    if text == "":
        return None

    ## Define the Polybius square
    polybius_square = [
        ["a", "b", "c", "d", "e"],
        ["f", "g", "h", "ij", "k"],
        ["l", "m", "n", "o", "p"],
        ["q", "r", "s", "t", "u"],
        ["v", "w", "x", "y", "z"],
    ]

    encrypted_text = ""

    for char in text:
        if char.isalpha():
            for i, row in enumerate(polybius_square):
                for j, ch in enumerate(row):
                    if char in ch:
                        encrypted_text += str(i + 1) + str(j + 1)
        else:
            encrypted_text += char

    return encrypted_text


if __name__ == "__main__":
    txt = input()
    print(polybius_encryption(txt))

You have now completed the implementation of the Polybius encryption algorithm. You can test your code by running the polybius.py file and providing input text to be encrypted.

  1. Run the polybius.py file and provide input text to be encrypted.
python3 polybius.py
  1. Observe the output of the encrypted text.
## Example 1
text = "tynam"; encryption_text = "4454331132"
## Example 2
text = "tynam123"; encryption_text = "4454331132123"
## Example 3
text = "TYnam"; encryption_text = "4454331132"
## Example 4
text = None; encryption_text = None

Congratulations! You have successfully implemented the Polybius encryption algorithm in Python.

Summary

Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.

Other Python Tutorials you may like