Implementing Affine Encryption in Python

PythonPythonBeginner
Practice Now

Introduction

In this project, you will learn how to implement the Affine Encryption algorithm in Python. The Affine Cipher is a type of substitution cipher that combines the characteristics of the shift cipher and the multiplier cipher. It uses a cryptographic function to encrypt one letter per letter, providing a simple yet effective way to encrypt and decrypt text.

👀 Preview

Sample 1: welcome - > oclsaqc
Sample 2: welcome - > oclsaqc
Sample 3: ïžąï―’we - > ïžąï―’oc
Sample 4: None - > None

ðŸŽŊ Tasks

In this project, you will learn:

  • How to implement the affine encryption function in Python
  • How to test the affine encryption function with sample inputs
  • How to encrypt user input using the affine encryption function

🏆 Achievements

After completing this project, you will be able to:

  • Understand the basic principles of the Affine Cipher
  • Implement the affine encryption algorithm in Python
  • Encrypt and decrypt text using the affine encryption function
  • Test the affine encryption function with various inputs

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) 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/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-302685{{"`Implementing Affine Encryption in Python`"}} python/variables_data_types -.-> lab-302685{{"`Implementing Affine Encryption in Python`"}} python/strings -.-> lab-302685{{"`Implementing Affine Encryption in Python`"}} python/conditional_statements -.-> lab-302685{{"`Implementing Affine Encryption in Python`"}} python/for_loops -.-> lab-302685{{"`Implementing Affine Encryption in Python`"}} python/function_definition -.-> lab-302685{{"`Implementing Affine Encryption in Python`"}} python/build_in_functions -.-> lab-302685{{"`Implementing Affine Encryption in Python`"}} end

Implement the Affine Encryption Function

In this step, you will learn how to implement the affine encryption function in Python. Follow the steps below to complete this step:

  1. Open the affine.py file in your text editor.
  2. Inside the affine_encryption(text) function, add the following code:
def affine_encryption(text: str) -> str:
    if text is None or text == "":
        return None

    a = 5
    b = 8
    m = 26
    encryption_text = ""

    for char in text:
        if "A" <= char <= "Z" or "a" <= char <= "z":
            char = char.lower()
            x = ord(char) - ord("a")
            y = (a * x + b) % m
            encryption_text += chr(y + ord("a"))
        else:
            encryption_text += char

    return encryption_text

Explanation:

  • The function first checks if the input text is None or an empty string. If so, it returns None.
  • The function then sets the values of a, b, and m as required by the affine encryption formula.
  • It iterates through each character in the input text.
  • If the character is a half-width English letter (between 'A' and 'Z', or 'a' and 'z'), it converts the character to lowercase, calculates the corresponding numerical value x, applies the affine encryption formula y = (a * x + b) % m, and appends the encrypted character to the encryption_text string.
  • If the character is not a half-width English letter, it is added to the encryption_text string without any modification.
  • Finally, the function returns the encryption_text string.
  1. Save the affine.py file.

Test the Affine Encryption Function

In this step, you will test the affine_encryption() function with the provided sample inputs.

  1. In the affine.py file, add the following code at the end of the file:
if __name__ == "__main__":
    ## Sample 1
    text = "welcome"
    encryption_text = affine_encryption(text)
    print(f"Sample 1: {text} -> {encryption_text}")

    ## Sample 2
    text = " welcome"
    encryption_text = affine_encryption(text)
    print(f"Sample 2: {text} -> {encryption_text}")

    ## Sample 3
    text = " ïžąï―’we"
    encryption_text = affine_encryption(text)
    print(f"Sample 3: {text} -> {encryption_text}")

    ## Sample 4
    text = None
    encryption_text = affine_encryption(text)
    print(f"Sample 4: {text} -> {encryption_text}")
  1. Save the affine.py file.
  2. Open a terminal or command prompt, navigate to the directory containing the affine.py file, and run the following command:
python3 affine.py

This will execute the affine_encryption() function with the provided sample inputs and print the results.

Verify that the output matches the expected results:

Sample 1: welcome -> oclsaqc
Sample 2:  welcome ->  oclsaqc
Sample 3:  ïžąï―’we -> ïžąï―’oc
Sample 4: None -> None

If the output matches the expected results, your affine_encryption() function is working correctly.

Encrypt User Input

In this step, you will modify the affine.py file to allow the user to input a text and encrypt it using the affine_encryption() function.

  1. In the affine.py file, replace the existing code at the end of the file (i.e., if __name__ == "__main__": and the portion that follows) with the following code:
if __name__ == "__main__":
    text = input("Enter the text to encrypt: ")
    encryption_text = affine_encryption(text)
    if encryption_text is None:
        print("Error: Input text is empty.")
    else:
        print(f"Encrypted text: {encryption_text}")

Explanation:

  • The code prompts the user to enter the text to be encrypted.
  • It then calls the affine_encryption() function with the user's input and stores the result in the encryption_text variable.
  • If the encryption_text is None (which means the input text was empty), it prints an error message.
  • Otherwise, it prints the encrypted text.
  1. Save the affine.py file.
  2. Open a terminal or command prompt, navigate to the directory containing the affine.py file, and run the following command:
python3 affine.py
  1. When prompted, enter a text to be encrypted, and observe the output.

Congratulations! You have completed the implementation of the affine encryption function and tested it with various inputs.

âœĻ Check Solution and Practice

Summary

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

Other Python Tutorials you may like